IE中的Javascript对象为null或不是对象

时间:2013-10-18 18:57:08

标签: javascript checkbox

我有一个表单,javascript添加了一个复选框,当提交表单时,它会检查复选框是否已勾选。这在Firefox或Chrome中运行良好,但在IE7或8中它会导致错误document.myform.mycheckbox.checked为null或不是对象。

var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name = "mycheckbox";
checkbox.value= 291;
var div = document.getElementById("addcb");
div.appendChild(checkbox);
checkbox.checked = false;

在表单标签中我有onSubmit =“return CheckForm();”,它在Firefox或Chrome中正常工作,但在IE7或8中它提交表单而不检查表单或其他表单对象。

if (document.myform.mycheckbox.checked == false){
    errorMsg += "\n\tAgree \t- Please Click I Agree Checkbox";
}

//If there is aproblem with the form then display an error
if ((errorMsg != "") || (errorMsgLong != "")){
    msg = "_______________________________________________________________\n\n";
    msg += "The form has not been submitted because there are problem(s) with the form.\n";
    msg += "Please correct the problem(s) and re-submit the form.\n";
    msg += "_______________________________________________________________\n\n";
    msg += "The following field(s) need to be corrected: -\n";

    errorMsg += alert(msg + errorMsg + "\n" + errorMsgLong);
    return false;
}

return true;

我使用Developer工具创建了一个报告错误的Brakpoint:

document.myform.mycheckbox.checked is null or not an object

1 个答案:

答案 0 :(得分:0)

创建它时,也要给它一个ID

checkbox.id = "mycheckbox";

然后找到它做

if (document.getElementById("mycheckbox").checked == false)