Javascript 如何使用javascript设置默认复选框状态?

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

How to set default checkbox status with javascript?

javascriptjquery

提问by Astronaut

I am used to doing this in jQuery

我习惯于在 jQuery 中这样做

$('#RememberMe').attr('checked', true); 

but I can't remember how to do it in Javascript I thought that

但我不记得如何在 Javascript 中做到这一点,我认为

document.getElementById("RememberMe").value = "True"; 

would work, but it doesn't, it changes the value but does not create the visual check on the html.

会工作,但它不会,它会更改值但不会在 html 上创建视觉检查。

I am trying to set the checkbox to on by default. here is the html

我试图将复选框设置为默认情况下。这是html

<input id="RememberMe" name="RememberMe" type="checkbox" value="false" />   

回答by VisioN

To change checkbox statetry this:

要更改复选框状态,请尝试以下操作:

document.getElementById("RememberMe").checked = true;

If you need to change the valueof checkbox as an inputelement use:

如果您需要将复选框的更改为input元素,请使用:

document.getElementById("RememberMe").value = "New Value";

However, you can set default value and state in HTML markup:

但是,您可以在 HTML 标记中设置默认值和状态:

<input id="RememberMe" name="RememberMe" type="checkbox" value="The Value" checked="checked" />