prodigerati
prodigerati

Reputation: 607

Read value from several checkboxs in a form using javascript

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...

Upvotes: 0

Views: 93

Answers (1)

Fabr&#237;cio Matt&#233;
Fabr&#237;cio Matt&#233;

Reputation: 70209

I would like to know if it's possible to loop through all toggles if I gave them the same ID?

No. IDs are unique. However, you can loop through them if you use a class.

Here's an example using hole_punch_buttons as a class:

<div class="btn-group hole_punch_buttons" data-toggle="buttons-radio">

And your rewritten JS:

$('div.hole_punch_buttons').each(function() {
    var n = $(this).find('input[value=1]').length;
    $(this).find('a[data-value=' + n + ']').addClass('active');
});

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:

$('div.hole_punch_buttons').each(function() {
    var n = $(this).find('input.hidden').val();
    $(this).find('a[data-value=' + n + ']').addClass('active');
});

Fiddle

Upvotes: 1

Related Questions