选中复选框的 Jquery DOM 设置适用于真而不是假

Jquery DOM setting checked in checkbox works for true not false

本文关键字:适用于 设置 复选框 Jquery DOM      更新时间:2023-09-26

我正在尝试将复选框的选中值设置为来自Mongo的传入数据。 如果值为 true,则它工作正常,但当值为 false 时,它仍然选中该框。 谁能告诉我出了什么问题。

<input type="checkbox" id="chk" name="interested" value="{{inmate.interested}}" onclick="chkSet(this)">Not Interested <br/>
<input type="checkbox" id="chk" name="correspondence" value="{{inmate.correspondence}}" onclick="chkSet(this)">Req Correspondence<br/>
<input type="checkbox" id="chk" name="study" value="{{inmate.study}}" onclick="chkSet(this)">Request Study<br/>
<input type="checkbox" id="chk" name="specialtyItemsApproved" value="{{inmate.specialtyItemsApproved}}" onclick="chkSet(this)">Specialty Items
Approved<br/>
<br>
$(document).ready(function(){
    document.getElementsByName("interested")[0].checked=document.getElementsByName("interested")[0].value;
    document.getElementsByName("correspondence")[0].checked=document.getElementsByName("correspondence")[0].value;
    document.getElementsByName("study")[0].checked=document.getElementsByName("study")[0].value;
    document.getElementsByName("specialtyItemsApproved")[0].checked=document.getElementsByName("specialtyItemsApproved")[0].value;
});
document.getElementsByName("interested")[0].checked=document.getElementsByName("interested")[0].value;根据

元素的值(始终为字符串)设置 checked 属性。所以它会将字符串强制为布尔值。所有非空字符串都是真实的,因此 "true""false" 都将checked设置为 true

如果使用==测试,则可以相应地设置checked

document.getElementsByName("interested")[0].checked =
    document.getElementsByName("interested")[0].value == "true";

也就是说,HTML/DOM 中复选框值的目的不是指示它是否被选中,因此首先将value设置为 "true""false" 可能不是您真正想要做的。value的目的是说明如果选中该复选框,应随表单一起发送什么值。例:

<input type="checkbox" name="roomoptions" value="non-smoking">
<input type="checkbox" name="roomoptions" value="with-kitchen">
<input type="checkbox" name="roomoptions" value="en-suite">

表单将具有roomoptions=non-smoking是否选中该复选框,和/或roomoptions=with-kitchen是否选中复选框,和/或roomoptions=en-suite是否选中复选框。如果未检查任何内容,则表单根本不会发送任何roomoptions。如果选中所有三个复选框,则发送所有三个复选框。

另外,不能对 HTML/DOM 文档中的多个元素使用相同的idid必须是唯一的。因此,您不能在所有复选框上使用id="chk"

所以我怀疑你真的想要更多这样的东西:

<input type="checkbox" id="chk-interested" name="interested" {{#if inmate.interested}}checked{{/if}} onclick="chkSet(this)">Not Interested <br/>
<input type="checkbox" id="chk-correspondence" name="correspondence" {{#if inmate.correspondence}}checked{{/if}}" onclick="chkSet(this)">Req Correspondence<br/>
<input type="checkbox" id="chk-study" name="study" {{#if inmate.study}}checked{{/if}} onclick="chkSet(this)">Request Study<br/>
<input type="checkbox" id="chk-specialty-items-approved" name="specialtyItemsApproved" {{#if inmate.specialtyItemsApproved}}checked{{/if}} onclick="chkSet(this)">Specialty Items

那么你根本不需要你的JavaScript。

我没有在这些上面放一个值,这意味着当表单被发送时(如果你在表单中发送),服务器将收到的interested值将是默认值"on"。 例如,表单要么根本没有interested字段(未选中复选框), 否则它将有interested=on.

请注意,除非您将这些id用于某些内容,否则您可以将其关闭;这是表单提交时将使用name。但我把它们做到了独特,以证明你必须这样做。