html元素数组是否为空

时间:2015-07-27 18:20:01

标签: javascript html css arrays

我有一个表单,其中有一个字段Work_Location [],它是一个数组。我想检查它是否为空。我做了

     var ele=document.myForm.elements['Work_Location[]'];
     alert(ele.length);
    if(ele.length==0)
    {
        alert("Please enter Work_Location");
        //document.myForm.EMail.focus() ;
        return false;
     }

alert(ele.length)打印undefined.whereas据我说它应该打印数组中的元素数

HTML代码

<form action="trainer_register.php" name="myForm" enctype="multipart/form-data" class="form-horizontal" method="post"  id="my-from" onsubmit="return validate();">
<div class="input_fields_wrap">
 <div class="form-group">
<label class="col-md-3 control-label" for="example-text-input">Preferred Work Location</label>
<div class="col-md-3">
<input type="text" id="loc" name="Work_Location[]" class="form-control" >
</div>
<button class="add_field_button">Add More Locations</button>
</div>
</div>

1 个答案:

答案 0 :(得分:3)

如果有多个与名称匹配的字段,则使用document.form.elements [&#34; name&#34;]返回一个数组,但如果只有一个元素,则返回该元素。< / p>

因此,如果定义了ele但未定义ele.length,那么就有一个结果。

尝试添加另一个,你会看到ele.length现在返回2.