jQuery After page loaded, check if radio button selected
Asked Answered
D

7

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?

Disenchant answered 7/9, 2013 at 7:15 Comment(1)
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.Ointment
L
20

Try with:

$(document).ready(function(){
    $("input[type=radio][name='q22']:checked").val()
});
Lutist answered 7/9, 2013 at 7:19 Comment(2)
Thanks, had it running under (window).load and wouldn't work but under .ready its fine - thanks!Disenchant
Just noticed that - ignore my previous comment.Disenchant
S
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

Sundried answered 7/9, 2013 at 7:22 Comment(0)
I
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

Illampu answered 7/9, 2013 at 7:19 Comment(0)
E
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

Espagnole answered 7/9, 2013 at 7:21 Comment(0)
G
1

try

var arr=$("input[type=radio][name=q22]:checked").map(function(){return $(this).val();})
Guesswork answered 7/9, 2013 at 7:23 Comment(0)
O
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
       }
    });
Ormand answered 7/9, 2013 at 7:18 Comment(0)
M
0

If you are using MVC try this

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

Maccaboy answered 9/11, 2022 at 14:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.