Error selecting switch using jQuery

I have this problem, I have 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 click the "Save" button, you should get the name idand value data-movt, but instead always gets the value of the first buttonradio

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

When I select the second switch, my error message is always displayed, 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? Is something missing? because it only works with the first switch, I can only select one switch, but I need to get the values ​​of the selected radio, I hope you can help me, thanks.

+4
source share
2 answers

... , [name="bank"].

    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');
    }

, "" JavaScript.

+1

, , . , , , $('[name="bank"]'), attr, attr , .

$(function(){
  $('#save-bank').click(function() {
      var count = 0;
      $('[name="bank"]').each(function(){
      
         if ($(this).prop('checked') == true) {
          
          var id   = $(this).attr('id');
          var movt = $(this).data('movt');

          alert(id + ' - ' + movt);

        } else{
           count++;
        }
      })
      if(count == 2) {
        alert('Select a radio button');
      }
     
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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 />
<button type="button" id="save-bank" class="btn-save">Save</button>
0

Source: https://habr.com/ru/post/1661898/


All Articles