jQuery 选中的复选框属性为真,但未显示勾号

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

Check box attributes checked is true, but tick is not shown

jqueryhtmlcheckbox

提问by gotqn

I have two check boxes, that I want to make to behave like they are radio buttons (only one of them is checked at time).

我有两个复选框,我想让它们表现得像单选按钮(一次只选中其中一个)。

So, I have easy found a jQuery solution that should do the trick:

所以,我很容易找到了一个应该可以解决问题的 jQuery 解决方案:

$("input:checkbox").click(function(){
    var group = "input:checkbox[name='"+$(this).attr("name")+"']";
    $(group).attr("checked",false);
    $(this).attr("checked",true);
});

The HTML looks like this:

HTML 如下所示:

<div class="radio">
    <label for="q_is_active_true">Is active</label>
    <input name="radio_buttons" type="hidden" value="0"><input id="q_is_active_true" name="radio_buttons" type="checkbox" value="1">
    <label for="q_is_active_false">Is not active</label>
    <input name="radio_buttons" type="hidden" value="0"><input id="q_is_active_false" name="radio_buttons" type="checkbox" value="1">
</div>

But when I click on one of the check boxes, even its "check" attribute is set to "checked" no tick is shown:

但是当我点击其中一个复选框时,即使它的“check”属性设置为“checked”也不会显示勾号:

回答by dsgriffin

You need to be setting the checked status by it's property to achieve what you want:

你需要用它的被设置检查状态道具erty达到你想要的东西:

$("input:checkbox").click(function(){
    var group = "input:checkbox[name='"+$(this).attr("name")+"']";
    $(group).prop("checked", false);
    $(this).prop("checked", true);
});

jsFiddle here.

jsFiddle在这里。

回答by Lalit Narayan Mishra

You can try it this way :

你可以这样试试:

$('input[name=checkBoxName]').parents('span').addClass("checked");
$("input[name=checkBoxName]").prop('checked', 'checked');

The first line is to display the tick in the check box and the second line is to actually check it.

第一行是在复选框中显示勾号,第二行是实际勾选它。