如何使用 jQuery 设置选中的单选选项如何使用、单选、选项、jQuery

2023-09-06 18:58:31 作者:情绪操控形象-

如何使用 jQuery 设置选中的单选选项?

How to set radio option checked onload with jQuery?

需要检查是否没有设置默认值,然后设置一个默认值

Need to check if no default is set and then set a default

推荐答案

假设你有这样的单选按钮,例如:

Say you had radio buttons like these, for example:

<input type='radio' name='gender' value='Male'>
<input type='radio' name='gender' value='Female'>

如果没有选中收音机,您想检查值为Male" onload 的那个:

And you wanted to check the one with a value of "Male" onload if no radio is checked:

$(function() {
    var $radios = $('input:radio[name=gender]');
    if($radios.is(':checked') === false) {
        $radios.filter('[value=Male]').prop('checked', true);
    }
});