Vlad Bardalez Vlad Bardalez - 8 months ago 34
jQuery Question

Event Listener for Multiple Radio Button Groups

How would you have a dynamic Javascript/JQuery event listener to know which radio button group is clicked and retrieve the value of the checked element. For example if I have two radio button groups how would I know which one is clicked? How would I do it for a dynamic number of button groups?

Example of two radio button groups:

<div class="btn-group btn-group-vertical" data-toggle="buttons">
<input type="radio" name="input1" value="option1"/>
<input type="radio" name="input1" value="option2"/>
<div class="btn-group btn-group-vertical" data-toggle="buttons">
<input type="radio" name="input2" value="option1"/>
<input type="radio" name="input2" value="option2"/>

Edit: For anyone else wondering which of the following question below so far is "more" right, both are correct as
.change(function(e) {
is a shortcut for
.on('click', function(e) {

Edit 2:Removed ID's


This jquery will execute a callback that print in the console the name and the value of the 'clicked' (not changed) radio button.

$('input:radio').on('click', function(e) {
    console.log(e.currentTarget.name); //e.currenTarget.name points to the property name of the 'clicked' target.
    console.log(e.currentTarget.value); //e.currenTarget.value points to the property value of the 'clicked' target.

try it: Fiddle