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
You can use a
change
handler for the radio buttons instead of aclick
handler for the labels.For example:
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.