jQuery 页面加载后,检查单选按钮是否被选中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18670813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:11:32  来源:igfitidea点击:

jQuery After page loaded, check if radio button selected

jqueryonloadchecked

提问by Homer_J

I can easily grab the valueor 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).

我可以使用 轻松抓取value或检查是否选择了单选按钮,.click(function()但是如果检查是否选择了单选按钮和/或在页面加载后获取其值(即某些单选按钮是预先设置的),我需要做什么在页面加载时选择)。

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

我认为这样的事情可能会起作用,但它不会:

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

Any suggestions?

有什么建议?

回答by Daniele

Try with:

尝试:

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

回答by Rikard

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.

您可能忘记的是在页面加载并读取 html 后运行它。您可以使用 jQuery 的.ready()来做到这一点。

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

Demohere

演示在这里

回答by cars10m

try

尝试

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

回答by T.J. Crowder

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

要么将您的脚本放在页面底部,就在结束</body>标记之前,要么使用 jQuery 的readyevent。在任何一种情况下,脚本都可以访问页面上的元素,并可以获得选中的单选按钮的值。

Gratuitous live example| source

无偿的活生生的例子| 来源

回答by Shakti Patel

used $(document).ready(handler)

用过的 $(document).ready(handler)

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

指定在 DOM 完全加载时要执行的函数。

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

BODY加载成功后会提示

回答by Bibhu

Try this :

尝试这个 :

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

or else you can also use this :

否则你也可以使用这个:

    $(function(){
       if ($("#radio1").is(":checked")) {
         // do something
       }
    });