【发布时间】:2012-03-07 12:15:08
【问题描述】:
我有一个简单的 HTML 文件,其中书位字段为数组,代码如下
<input type="checkbox" name="book[]" value="<?php echo $i; ?> /><?php echo $i; ?>
<input type="submit" value="BOOK" onclick = "checkIfSeatEmpty()" />
我用来验证字段book是否为空的javascript是:
var x=document.forms["bkfrm"].getElementById("chkbx").value;
//alert(x); alerts 'undefined' !
// var x=document.forms["bkfrm"].getElementById("book").length;
alert(x);
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
return TRUE;
但是上面的代码警告为undefined!如何检查该字段是否为空?
【问题讨论】:
-
您的代码中没有这样的 id 'chkbx'。
-
只需添加 id="book"。在您的代码中只有 name 属性,但没有 id 属性。 getElementById 按 id 搜索元素。
-
在调用
getElementById之前应该不需要导航到document.forms["bkfrm"]。元素 ID 应该是唯一的,因此document.getElementById('chkbx')应该足够了。如果您在单个页面中有多个具有相同 id 的元素,则会生成无效代码。此外,使用document.getElementById而不是document.forms["bkfrm"].getElementById也会更快。
标签: javascript html arrays validation