简体   繁体   中英

array of html elements empty or not

I have a form in which I have a field Work_Location[] which is an array. I want to check if it is empty or not. I did

     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) prints undefined.whereas according to me it should print number of elements in the array

HTML code

<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>

Using document.form.elements["name"] returns an array if there are more than one fields matching the name, but just returns the element itself if there's only one element.

So if ele is defined but ele.length is not defined, then there is one result.

Try adding another and you'll see that ele.length now returns 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM