Fixer Fixer - 14 days ago 11
HTML Question

Error selecting radio button with jQuery

I have this problem, I got these radio buttons

<input type="radio" name="bank" id="bank-1" data-movt="0"> Bank 1 <br />
<input type="radio" name="bank" id="bank-2" data-movt="0"> Bank 2 <br />


And when I press my "Save" button it is suppose to get the name of the
id
and the value of
data-movt
, but instead of that always gets the value of the first
radio
button

<button type="button" id="save-bank" class="btn-save">Save</button>


When I select the second radio button always display my error message, this is my jQuery code:

$('#save-bank').click(function() {

if ($('[name="bank"]').prop('checked') == true) {

var id = $('[name="bank"]').attr('id');
var movt = $('[name="bank"]').data('movt');

alert(id + ' - ' + movt);

} else {

alert('You need to select a bank');
}
});


Am I doing something wrong? missing something? because it only works with the first radio button, I only can choose one radio button, but I need to get the values of the selected radio, I hope you can help me, thanks.

Answer

Try ... this should provide the single element, rather than all the [name="bank"] elements.

    if ($('[name="bank"]:checked')) {
      var id   = $('[name="bank"]:checked').attr('id');
      var movt = $('[name="bank"]:checked').data('movt');
      alert(id + ' - ' + movt);
    } else {
      alert('You need to select a bank');
    }

While you could loop through all the elements, this is a simpler way to select the correct "single" element without the overhead of JavaScript looping.