Javascript 使用javascript更改复选框的“已检查”属性

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

changing ''checked' attribute of a checkbox using javascript

javascripthtmlajaxjsp

提问by bouncingHippo

right now when it first loads the html page, my checkbox was created in this way:

现在,当它第一次加载 html 页面时,我的复选框是这样创建的:

<input type="checkbox" id="CBOX1" name="CBOX1" onclick="onCBOX(this)" disabled/>

in a function in on the same html:

在同一个 html 的函数中:

boolean checked = true;
document.theForm.elements['CBOX1'].checked = true;

For some reason, the checked box value is not checked when the function is called later on the page. Is it because when i first created the checkbox, i created it without a 'checked' attribute? And then when i assign it a value, the element doesnt seem to include the checked attribute anymore as when i check on the source of the page. its still the same...

出于某种原因,稍后在页面上调用该函数时,不会选中复选框值。是不是因为当我第一次创建复选框时,我创建的它没有“选中”属性?然后当我为其分配一个值时,该元素似乎不再像我检查页面源时那样包含已检查的属性。还是一样...

<input type="checkbox" id="CBOX1" name="CBOX1" onclick="onCBOX(this)" disabled/>

For simplicity sake, i know for sure that there were changes made to other attributes of this element using AJAX, but i am at a loss to WHY the checked attribute is not carried over... What's the alternative?

为简单起见,我确定使用 AJAX 对该元素的其他属性进行了更改,但我不知道为什么未结转已检查的属性......有什么替代方法?

回答by Travis J

Check the checkbox:

选中复选框:

document.theForm.elements['CBOX1'].checked = true;
document.theForm.elements['CBOX1'].checked = "checked"; 

Uncheck the checkbox:

取消选中复选框:

document.theForm.elements['CBOX1'].checked = false; 

If you want it unchecked on load then don't touch it, by default it is unchecked.

如果您希望在加载时取消选中它,请不要触摸它,默认情况下它是未选中的。

Moreover, no click events will be registered if you use the disabledattribute on your input field.

此外,如果您在输入字段上使用disabled属性,则不会注册任何点击事件。

See this jsfiddlefor an example.

有关示例,请参阅此jsfiddle

EDIT

编辑

If clickability is not the issue then just do what I already pointed out. Here is a fullworking example.

如果可点击性不是问题,那么只需执行我已经指出的操作。这是一个完整的工作示例。

<html>
 <head>
 </head>
 <body>
  <input id="tar" type="checkbox" disabled />
  <input type="checkbox" onclick="callFunc(this)" />
  <script type="text/javascript">
   function callFunc(elem){
    document.getElementById("tar").checked = elem.checked;
   }
  </script>
 </body>
</html>

回答by RedFilter

Try setting it to trueinstead:

尝试将其设置为true

document.theForm.elements['CBOX1'].checked = true; 

回答by Uchenna Nwanyanwu

Try this, not tested anyway.

试试这个,反正没有测试。

document.theForm.elements['CBOX1'].checked = true;