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?

有帮助吗?

解决方案

Try with:

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

其他提示

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

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

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

try

var arr=$("input[type=radio][name=q22]:checked").map(function(){return $(this).val();})

Try this :

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

or else you can also use this :

    $(function(){
       if ($("#radio1").is(":checked")) {
         // do something
       }
    });
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top