7

I can easily grab the value or check if a radio button is selected using the .click(function() but what I need to do if check to see if a radio button is selected and/ or grab its value after a page has loaded (i.e. some radio buttons are pre-selected on page load).

I assumed something like this might work but it doesn't:

$("input[type=radio][name=q22]:checked").val()

Any suggestions?

Daniele
  • 1,938
  • 16
  • 24
Homer_J
  • 3,277
  • 12
  • 45
  • 65
  • I forgot to copy something in my original answer, in case you saw it before I quickly corrected it. Updated that. I included some other nice functionality you may be interested in. – m59 Sep 07 '13 at 07:34

7 Answers7

20

Try with:

$(document).ready(function(){
    $("input[type=radio][name='q22']:checked").val()
});
Daniele
  • 1,938
  • 16
  • 24
6

Your code is ok.

What you might have forgoten is to run it after page has loaded and the html has been read. You can use jQuery's .ready() to do this.

$(document).ready(function () {
    var i = $("input[type=radio][name=q22]:checked").val();
    console.log(i);
});

Demo here

Rikard
  • 7,485
  • 11
  • 55
  • 92
1

Either just put your script at the bottom of the page, just before the closing </body> tag, or use jQuery's ready event. In either case, the script will have access to the elements on the page and can get the value of the checked radio button.

Gratuitous live example | source

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

used $(document).ready(handler)

Specify a function to execute when the DOM is fully loaded.

Check This

$(document).ready(function() {
    // Handler for .ready() called.
    // Code run after DOM load success 
});


<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  alert("")
});
</script>
</head>
<body>
</body>
</html>

it will alert after BODY loaded success

Shakti Patel
  • 3,762
  • 4
  • 22
  • 29
1

try

var arr=$("input[type=radio][name=q22]:checked").map(function(){return $(this).val();})
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
0

Try this :

$(function(){
    $("input[type=radio][name='q22']:checked").val();
});

or else you can also use this :

    $(function(){
       if ($("#radio1").is(":checked")) {
         // do something
       }
    });
Bibhu
  • 4,053
  • 4
  • 33
  • 63
0

If you are using MVC try this

var d= $('[name="@Html.NameFor(m => m.City)"]:checked').val();

Devanathan.S
  • 1,362
  • 1
  • 14
  • 22