[英]javascript dynamic checkbox checking
I have a form (id="myForm") whose checkbox ("checkbox") I check/uncheck as follows: 我有一个表单(id =“ myForm”),其复选框(“ checkbox”)的检查/取消选择如下:
document.forms['myForm'].checkbox.checked = false;
How can I do this dynamically? 我如何动态地做到这一点? Ie have a function where I pass in the name of the checkbox and then check or uncheck it? 即有一个功能,我可以传入复选框的名称,然后选中还是取消选中它?
function check(name) {
document.forms['myForm'].**name**.checked = false; // how can I do this right?
}
In Javascript, foo.bar
is equivalent to foo["bar"]
, thus you can use: 在Javascript中, foo.bar
等效于foo["bar"]
,因此您可以使用:
document.forms['myForm'][checkboxName].checked = false;
However, it is more direct if you can give each checkbox a unique id
, and use 但是,如果您可以为每个复选框指定唯一的id
并使用,则更为直接
document.getElementById(checkboxId).checked = false;
You can create a simple function like this and pass in the ID
of the checkbox and the resulting state whether or not the checkbox should be checked. 您可以创建一个像这样的简单函数,并传递复选框的ID
和结果状态,无论是否应选中该复选框。
function checkTheBox(id, checkState)
{
var checkbox = document.getElementById(id);
if(checkbox)
checkbox.checked = checkState;
}
This sample also includes some error checking to ensure that the checkbox exists before attempting to set the checked
flag. 此示例还包括一些错误检查,以确保在尝试设置checked
标志之前,该复选框已存在。
尝试这个
document.forms['myForm'].**name**.defaultChecked = true;
Like this: 像这样:
function checkuncheck(formName, checkName, status)
{
document.forms[formName][checkName].checked = status;
}
Where you pass status
as either true
to make it checked or false
to make it unchecked. 您将status
传递为true
表示选中,否则返回false
表示取消选中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.