Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .change() on Radio Button

I must be missing something obvious here... I can't get .change() to fire on radio buttons? I have the code below live here!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>     <title>Radio Button jQuery Change</title>     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>     <script type="text/javascript">         console.log("parsed");         $("input[name='rdio']").change(function() {             console.log("changed");             if ($("input[name='rdio']:checked").val() == 'a')                 $("output").text("a changed");             else if ($("input[name='rdio']:checked").val() == 'b')                 $("output").text("b changed");             else                 $("output").text("c changed");         });     </script> </head> <body>     <div>         <input type="radio" name="rdio" value="a" checked="checked" /> a <br/>         <input type="radio" name="rdio" value="b" /> b <br/>         <input type="radio" name="rdio" value="c" /> c     </div>     <h3>Output:</h3>     <div id="output"></div> </body> </html> 

Can anyone see what I've missed?

Thanks, Denis

like image 979
Denis Hoctor Avatar asked Apr 15 '10 10:04

Denis Hoctor


People also ask

How to detect change in radio button in jQuery?

Now, to detect when that radio box is changed, you can easily call the jQuery 'change' event inside your jQuery document ready function: $(document). ready(function(){ $('#my_radio_box'). change(function(){ alert('Radio Box has been changed!

How to set radio button value using jQuery?

$('input:radio[name=cols]'+" #"+newcol). attr('checked',true);


1 Answers

You must put the code inside the dom-ready event...

 $(document).ready(function(){    // Your code here  }); 

or else the script gets executed before the HTML-elements have been loaded. Thus, no radioboxes exist.

like image 67
Mickel Avatar answered Sep 19 '22 19:09

Mickel