将单选按钮设置为签入jquery,而不将其显示为签入视图

Setting a radio button to checked in jquery not showing it as checked in view

本文关键字:视图 显示 jquery 单选按钮 设置      更新时间:2023-09-26

在文档就绪时,我将一个单选按钮设置为选中,我希望用户看到该按钮高亮显示/变色。但视野中什么也看不到。这是我的html。在视图或HTML中,没有任何内容显示它已被选中。它和所有其他单选按钮的颜色相同。

<div class="btn-group" data-toggle="buttons" id="SpaceType">
                    <label class="btn btn-primary">
                        <input type="radio" name="typeoptions" id="0" autocomplete="off"> House
                    </label>
                    <label class="btn btn-primary">
                        <input type="radio" name="typeoptions" id="1" autocomplete="off"> Apartment
                    </label>
                    <label class="btn btn-primary">
                        <input type="radio" name="typeoptions" id="2" autocomplete="off"> Studio
                    </label>
                    <label class="btn btn-primary">
                        <input type="radio" name="typeoptions" id="3" autocomplete="off"> Other
                    </label>
                </div>

这是我的jquery。

if ($("#YogaSpaceType").val() != "") {
    var t = $("#YogaSpaceType").val();
    var element = '#SpaceType.' + t;
    //$(element).prop('checked', true);
    $('input:radio[id=SpaceType][id=0]').prop('checked', true);
}

我试了两行,包括被注释掉的那一行。如果我像下面这样将"checked"添加到元素中,HTML会将其显示为checked,但我在视图中看不到任何内容,它看起来仍然是未检查的。

<input type="radio" name="typeoptions" id="0" autocomplete="off" checked> House

看起来你想把它改得更像http://www.mkyong.com/jquery/how-to-select-a-radio-button-with-jquery/.这里的问题是您试图在jquery中使用input关键字,但您的html是按钮组。

在该页面中,HTML是: <input type="radio" name="sex" value="Male">Male</input> <input type="radio" name="sex" value="Female">Female</input> <input type="radio" name="sex" value="Unknown">Unknown</input>

则JS为$('input:radio[name=sex]')[2].checked = true;

如果有必要将它们保留为按钮组,则需要将JS行更改为更像$("#0").prop('checked', true)。您也可以像这样将div id链接在一起:$("#SpaceType#0").prop("checked",true);

这有点令人困惑,但需要将class属性'active'添加到标签中。不是选中的属性。这有点令人困惑,但现在已经理解了。

$('input[type="radio"][id="0"]').prop('checked', true)

id的多值检查将以0个元素结束。