1

I try this way for get a value from radiobuttons (iCheck), but all the time only return the value from the first radio, ignoring the remaining. The theory says that the code is fine, even so it returns badly.

Radio box, get the checked value [iCheck]

My code:

<div class="step row">
  <div class="col-md-10">
    <h3>YYYYYY.</h3>
    <ul class="data-list-2">
      <li><input name="p1" id="p1" type="radio" class="required check_radio" value="1"><label>Yes</label></li>
      <li><input name="p1" id="p1" type="radio" class="required check_radio" value="0"><label>No</label></li>
      <li><input name="p1" id="p1" type="radio" class="required check_radio" value="2"><label>Meybe</label></li>
    </ul>
  </div>
</div>
<!-- end step -->

My method for get value:

$(document).ready(function() {
  $('#p1').on('ifChecked', function(event) { //try ifClicked - ifToggled 
    alert($(this).val()); // alert value
  });
});

All the time return value 1 even when another option is selected.

Please help, I try all the night different ways but doesn't work ;(

Rick
  • 4,030
  • 9
  • 24
  • 35
Alejandro
  • 13
  • 4
  • 1
    You're using multiple identical IDs (`p1`). Use classes instead. – Fissure King Jul 18 '18 at 17:15
  • @Alejandro You have the same id value of "p1" for all your radio buttons. Ids should always be unique. If you want to add the 'ifChecked' event handler to all your radio buttons, change from `$('#p1')` to `$('.required.check_radio')` so that you use the class and attach event handlers to all radio buttons, # stands for id, since you have multiple with the same id, it just defaults to the first one. – Ryan Wilson Jul 18 '18 at 17:16
  • Can you give me an example please, I'm new to this, I use the ID because I have many "step row" divs with different questions and p2,p3,p4 ....., this is a survey – Alejandro Jul 18 '18 at 17:19
  • @Alejandro I provided the relevant code in an answer below. – Ryan Wilson Jul 18 '18 at 17:29

1 Answers1

1

I'm not sure how you are generating the ids for your radio buttons, but the id property should always be unique, since you want the same event handling on your radio buttons, just use the class so that it attaches the event to all your radio buttons which belong to that class, then you don't have to add events for each individual id:

So instead of this:

//If you did it this way, you'd have to have one of these blocks for each
//unique id belonging to a radio button
$('#p1').on('ifChecked', function(event){ //try ifClicked - ifToggled 
  alert($(this).val()); // alert value
});

Change it to this:

//Use the class instead so that the same event handling can be added to all radio
//buttons in one block of code
$('.required.check_radio').on('ifChecked', function(event){ //try ifClicked - ifToggled 
  alert($(this).val()); // alert value
});
Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40