skip to Main Content

I came up with a way to get the value of the radio button by connecting for and id.
But I couldn’t come up with a method other than using for.

<script src="https://code.jquery.com/jquery-3.7.0.js"></script>

<div>
  <input type="radio" name="group" value="1" id="id_1" checked>
  <input type="radio" name="group" value="2" id="id_2">
  <input type="radio" name="group" value="3" id="id_3">

  <ul>
    <li><label for="id_1">id_1</label></li>
    <li><label for="id_2">id_2</label></li>
    <li><label for="id_3">id_3</label></li>
  </ul>
</div>

<script>
  jQuery(function($) {
    $('label').on('click', function(){
      // Not working as intended
      console.log(`Not working as intended: ${$(this).parents('div').find('input:checked').val()}`);
      console.log($("input[name='group']:checked").val());

      // It works.But I want to know how to not use for
      console.log(`It works: ${$(`input#${$(this).attr('for')}`).val()}`);
    });
  });
</script>

2

Answers


  1. You can use a change handler for the radio buttons instead of a click handler for the labels.

    For example:

    $('input[name="group"]').on('change', function() {
      var value = $(this).val();
      console.log(value);
    });
    
    Login or Signup to reply.
  2. What’s happening is you are handling the click on the label and reporting before the radio button selection actually changes.

    Instead of binding to click on the label, bind an event handler to the change event on the radio buttons themselves.

    <script src="https://code.jquery.com/jquery-3.7.0.js"></script>
    
    <div>
      <input type="radio" name="group" value="1" id="id_1" checked>
      <input type="radio" name="group" value="2" id="id_2">
      <input type="radio" name="group" value="3" id="id_3">
    
      <ul>
        <li><label for="id_1">id_1</label></li>
        <li><label for="id_2">id_2</label></li>
        <li><label for="id_3">id_3</label></li>
      </ul>
    </div>
    
    <script>
      jQuery(function($) {
        $('input[type=radio]').on('change', function() {
            let div = $(this).parents('div')[0];
            console.log('the parent div is:', div);
            let selected = div.querySelector('input[type=radio]:checked');
            console.log('selected is:', selected);
        });
      });
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search