如何设置单选选项检查 onload 与 jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/871063/
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 09:58:43  来源:igfitidea点击:

how to set radio option checked onload with jQuery

jqueryradio-button

提问by Phill Pafford

How to set radio option checked onload with jQuery?

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

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

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

回答by Paolo Bergantino

Say you had radio buttons like these, for example:

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

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

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);
    }
});

回答by Andrew McCombe

How about a one liner?

一个班轮怎么样?

$('input:radio[name="gender"]').filter('[value="Male"]').attr('checked', true);

回答by chaiko

This one will cause form.reset() failure:

这将导致 form.reset() 失败:

$('input:radio[name=gender][value=Male]').attr('checked', true);

But this one works:

但是这个有效:

$('input:radio[name=gender][value=Male]').click();

回答by Shital Shah

JQuery has actually two ways to set checked status for radio and checkboxes and it depends on whether you are using value attribute in HTML markup or not:

JQuery 实际上有两种方法来设置单选框和复选框的选中状态,这取决于您是否在 HTML 标记中使用 value 属性:

If they have value attribute:

如果它们具有 value 属性:

$("[name=myRadio]").val(["myValue"]);

If they don't have value attribute:

如果他们没有 value 属性:

$("#myRadio1").prop("checked", true);

More Details

更多细节

In first case, we specify the entire radio group using name and tell JQuery to find radio to select using val function. The val function takes 1-element array and finds the radio with matching value, set its checked=true. Others with the same name would be deselected. If no radio with matching value found then all will be deselected. If there are multiple radios with same name and value then the last one would be selected and others would be deselected.

在第一种情况下,我们使用 name 指定整个无线电组,并告诉 JQuery 使用 val 函数查找要选择的无线电。val 函数采用 1 元素数组并找到具有匹配值的收音机,将其设置为 checked=true。其他同名的将被取消选择。如果没有找到具有匹配值的无线电,则所有无线电都将被取消选择。如果有多个具有相同名称和值的无线电,则将选择最后一个并取消选择其他无线电。

If you are not using value attribute for radio then you need to use unique ID to select particular radio in the group. In this case, you need to use prop function to set "checked" property. Many people don't use value attribute with checkboxes so #2 is more applicable for checkboxes then radios. Also note that as checkboxes don't form group when they have same name, you can do $("[name=myCheckBox").prop("checked", true);for checkboxes.

如果您没有为收音机使用 value 属性,那么您需要使用唯一 ID 来选择组中的特定收音机。在这种情况下,您需要使用 prop 函数来设置“已检查”属性。许多人不将 value 属性与复选框一起使用,因此 #2 更适用于复选框而不是收音机。另请注意,由于复选框在名称相同时不会形成组,因此您可以$("[name=myCheckBox").prop("checked", true);对复选框进行操作。

You can play with this code here: http://jsbin.com/OSULAtu/1/edit?html,output

你可以在这里玩这个代码:http: //jsbin.com/OSULAtu/1/edit?html,output

回答by clayzermk1

I liked the answer by @Amc. I found the expression could be condensed further to not use a filter() call (@chaiko apparently also noticed this). Also, prop() is the way to go vs attr() for jQuery v1.6+, see the jQuery documentation for prop()for the official best practices on the subject.

我喜欢@Amc 的回答。我发现可以进一步压缩表达式以不使用 filter() 调用(@chaiko 显然也注意到了这一点)。此外,对于 jQuery v1.6+,prop() 是与 attr() 相比的方法,有关该主题的官方最佳实践,请参阅prop()jQuery 文档

Consider the same input tags from @Paolo Bergantino's answer.

考虑来自@Paolo Bergantino 的回答的相同输入标签。

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

The updated one-liner might read something like:

更新后的单行可能是这样的:

$('input:radio[name="gender"][value="Male"]').prop('checked', true);

回答by Saram

I think you can assume, that name is unique and all radio in group has the same name. Then you can use jQuery support like that:

我想您可以假设,该名称是唯一的,并且组中的所有收音机都具有相同的名称。然后你可以像这样使用 jQuery 支持:

$("[name=gender]").val(["Male"]);

Note:Passing array is important.

注意:传递数组很重要。

Conditioned version:

条件版本:

if (!$("[name=gender]:checked").length) {
    $("[name=gender]").val(["Male"]);
}

回答by WildSpidee

If you want it to be truly dynamic and select the radio that corresponds to the incoming data, this works. It's using the gender value of the data passed in or uses default.

如果您希望它真正动态并选择与传入数据相对应的无线电,这很有效。它使用传入数据的性别值或使用默认值。

if(data['gender'] == ''){
 $('input:radio[name="gender"][value="Male"]').prop('checked', true);
}else{
  $('input:radio[name="gender"][value="' + data['gender'] +'"]').prop('checked', true);
};

回答by Razan Paul

Native JS solution:

原生JS解决方案:

 document.querySelector('input[name=gender][value=Female]').checked = true;

http://jsfiddle.net/jzQvH/75/

http://jsfiddle.net/jzQvH/75/

HTML:

HTML:

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

回答by Iftikhar

And if you want to pass a value from your model and want to select a radio button from the group on load based on value, than use:

如果你想从你的模型中传递一个值并想从基于值的加载组中选择一个单选按钮,那么使用:

Jquery:

查询:

var priority = Model.Priority; //coming for razor model in this case
var allInputIds = "#slider-vertical-" + itemIndex + " fieldset input";

$(allInputIds).val([priority]); //Select at start up

And the html:

和 html:

<div id="@("slider-vertical-"+Model.Id)">
 <fieldset data-role="controlgroup" data-type="horizontal" data-mini="true">
    <input type="radio" name="@("radio-choice-b-"+Model.Id)" id="@("high-"+Model.Id)" value="1" checked="checked">
    <label for="@("high-"+Model.Id)" style="width:100px">@UIStrings.PriorityHighText</label>

    <input type="radio" name="@("radio-choice-b-"+Model.Id)" id="@("medium-"+Model.Id)" value="2">
    <label for="@("medium-"+Model.Id)" style="width:100px">@UIStrings.PriorityMediumText</label>

    <input type="radio" name="@("radio-choice-b-"+Model.Id)" id="@("low-"+Model.Id)" value="3">
    <label for="@("low-"+Model.Id)" style="width:100px">@UIStrings.PriorityLowText</label>
 </fieldset>
</div>

回答by karma

Here is example with above methods:

以下是上述方法的示例:

<div class="ui-field-contain">
<fieldset data-role="controlgroup" data-type="horizontal">    <legend>Choose a pet:</legend>
    <input type="radio" name="radio-choice-2" id="radio-choice-1" value="choice1">
    <label for="radio-choice-1">Cat</label>

    <input type="radio" name="radio-choice-2" id="radio-choice-2" value="choice2">
    <label for="radio-choice-2">Dog</label>

    <input type="radio" name="radio-choice-2" id="radio-choice-3" value="choice3">
    <label for="radio-choice-3">Hamster</label>

    <input type="radio" name="radio-choice-2" id="radio-choice-4" value="choice4">
    <label for="radio-choice-4">Lizard</label>
  </fieldset>
</div>

In javascript:

在 JavaScript 中:

$("[name = 'radio-choice-2'][value='choice3']").prop('checked', true).checkboxradio('refresh');