Radio button adds class

This example shows how to add/remove classes dynamically. In this case by using radio buttons.

In this example, a list of radio buttons is presented. When a radio button is selected, its parent element (a LABEL) gets styled with the chosen class.

In this example, the chosen class is styled using following CSS style sheet:

.chosen{ font-weight: bold; }

Since selecting a radio button automatically deselects the radio buttons in the same group (with the same name), we have to remove the chosen class from the other radio buttons so only the selected radio button pops out.

This is done using the ifchecked-removeclass event-action attribute. It removes the chosen class from all labels within the options section (as the "#options label" CSS selector selects all LABEL elements underneath the element with id "options").

Then the ifchecked-addclass event-action of the checked radio button is executed, which uses a relative CSS selector ("<label") to add the chosen class on it's parent LABEL element.

~-removeclass event-actions for the same event type and on the same element, are always processed before ~-addclass event-actions. Therefore it is safe to first remove the chosen class from all labels, and then add the class again to the single label surrounding the currently selected radio button.

In this example, the label surrouding the checked radio button gets a class chosen:

<div id="options">
  <div>
    <label>
      <input type="radio" name="options" value="1" checked
             ifchecked-removeclass="chosen on #options label"
             ifchecked-addclass="chosen on <label" >
      Option 1
    </label>
  </div>
  <div>
    <label>
      <input type="radio" name="options" value="2"
             ifchecked-removeclass="chosen on #options label"
             ifchecked-addclass="chosen on <label" >
      Option 2
    </label>
  </div>
  <div>
    <label>
      <input type="radio" name="options" value="3"
             ifchecked-removeclass="chosen on #options label"
             ifchecked-addclass="chosen on <label" >
      Option 3
    </label>
  </div>
</div>

Notice that the first option is initially checked. The ifchecked-~ event-actions are also evaluated on load such that the chosen class will be added to the first label as soon as the page gets loaded.

 

Working demo
Loading demo...

 

Requirements

This example requires following Sircl library files to be loaded:

or:

Or their non-minified counterparts.

See the Get Started section about how to set up your project to use the Sircl library.