简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM