I’m very new to javascript and have a question. I am using twitter bootstrap, rails and simpleform. I replaced checkboxes with toggles using javascript in my form. I am now trying to display the correct toggle option to the user using the same form when I edit.
When the form is displayed in the edit action, the toggle is selected for the checkbox value (1 or 0). The JS code below works for a single toggle element. I would like to know if it’s possible to loop through all toggles if I gave them the same ID? I have more then 10 checkboxes in my form and don’t want to duplicate JS.
var n = $('#hole_punch_buttons input[value=1]').length;
if(n === 1){
$("#hole_punch_buttons a[data-value=1]").addClass('active')
}
else {
$("#hole_punch_buttons a[data-value=0]").addClass('active')
}
Here is the HTML:
<div id="hole_punch_buttons" class="btn-group" data-toggle="buttons-radio">
<div class="control-group hidden">
<div class="controls">
<input class="hidden" id="id_card_design_hole_punch" name="id_card_design[hole_punch]" type="hidden" value="1">
</div>
</div>
<a class="btn ffbtn active" data-value="1">Yes</a>
<a class="btn sfbtn" data-value="0">No</a>
</div>
Maybe there is a better way to write it altogether…
No. IDs are unique. However, you can loop through them if you use a class.
Here’s an example using
hole_punch_buttonsas a class:And your rewritten JS:
Fiddle
Another solution is to use
.val()to retrieve the value of the hidden input and add the active class to the corresponding anchor’s data-value:Fiddle