Click or change the event on the radio using jquery

I have several radio stations on my page, and I want to do something when the checked radio changes, however the code does not work in IE:

$('input:radio').change(...); 

And after googling, people suggest using click . But that does not work.

This is a sample code:

 <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> <script type="text/javascript"> $('document').ready( function(){ $('input:radio').click( function(){ alert('changed'); } ); } ); </script> </head> <body> <input type="radio" name="testGroup" id="test1" />test1<br/> <input type="radio" name="testGroup" id="test2" />test2<br/> <input type="radio" name="testGroup" id="test3" />test3</br> </body> </html> 

It also does not work in IE.

So, I want to know what is going on?

Also, I'm afraid if he will restart the change event, if I click on the checked radio?

UPDATE:

I can not add a comment, so I answer here.

I am using IE8, and the Furqan link gives me also does not work in IE8. I do not know why...

+75
jquery radio-button
Mar 02 '11 at 10:00
source share
5 answers

This code worked for me:

 $(function(){ $('input:radio').change(function(){ alert('changed'); }); }); 

http://jsfiddle.net/3q29L/

+101
Mar 02 2018-11-11T00:
source share

You can specify a name attribute, as shown below:

 $( 'input[name="testGroup"]:radio' ).change( 
+66
Sep 07 '13 at 23:28
source share

Works for me too, here is the best solution:

script demonstration

 <form id="myForm"> <input type="radio" name="radioName" value="1" />one<br /> <input type="radio" name="radioName" value="2" />two </form> <script> $('#myForm input[type=radio]').change(function() { alert(this.value); }); </script> 

You have to make sure that you initialize jquery above all other import and javascript functions. Because $ is a jquery function. Even

 $(function(){ <code> }); 

doesn't check jquery initialization or not. It ensures that <code> will only be run after all javascripts are initialized.

+12
Apr 02 '14 at 5:15
source share

Try

 $(document).ready( 

instead

 $('document').ready( 

or you can use the short form

 $(function(){ }); 
+7
Mar 02 '11 at 10:10
source share

 $( 'input[name="testGroup"]:radio' ).on('change', function(e) { console.log(e.type); return false; }); 

This syntax is slightly more flexible for event handling. You can not only observe the β€œchanges”, but other types of events can be controlled here using one event handler. You can do this by passing a list of events as arguments to the first parameter. See jQuery On.

Secondly, .change () is a shortcut for .on ("change", handler). See here . I prefer to use .on () rather than .change because I have more control over events.

Finally, I just show an alternative syntax for attaching an event to an element.

-2
Jun 14 '16 at 17:39
source share



All Articles