Jackie
Jackie

Reputation: 457

Click event on radio buttons jquery

I have looked for few other answers and tutorials but havent been able to find what I want. For example, I found this which uses change function, however, I need to use a click event and detect when a radio button is clicked. When a radio button is click I will be showing message to show like "you have selected radio button 1".

For example, below are my 3 radio buttons and I want to assign click event to them

<input type="radio" name="one" value="first" id="radio1" checked> first
<input type="radio" name="two" value="second" id="radio2" checked> second
<input type="radio" name="three" value="third" id="radio3" checked> third

I have tried

1

var inputs = document.querySelectorAll('input');
for (var i = 0; i <= inputs.length; i++) {
     $("input[id='radio'+i]").click(function(){
        if(inputs == 'radio1') {
           //dosomething
        } else if (inputs == 'radio2') {
          //dosomething
        }else if (inputs == 'radio3') {
          //dosomething
        }
     });
}

2

  var inputs = document.querySelectorAll('input');
  for (var i = 0; i <= inputs.length; i++) {
        $("#radio"+i).click(function(){
            if(inputs == 'radio1') {
               //dosomething
            } else if (inputs == 'radio2') {
              //dosomething
            }else if (inputs == 'radio3') {
              //dosomething
            }
        });

    } 

Please can someone help me on this as I have searched but havent been able to find anything of help.

Upvotes: 0

Views: 1243

Answers (1)

D. Seah
D. Seah

Reputation: 4592

you do not have radio buttons group of different names. You are likely to have something like this

<form id="myForm">
<input type="radio" name="radio" value="first" checked> first
<input type="radio" name="radio" value="second"> second
<input type="radio" name="radio" value="third"> third
</form>

$('#myForm input').on("change", function() {
    console.log($(this).attr('value')); // based on the value do something.
});

thanks

Upvotes: 1

Related Questions