开发者

Iterating through same form elements

If a form has same tag repeatedly, how to get its value in JavaScript?

    <script>
     function validate()
      {
        //get all values of elmone
      }
     </script>


<form>
<input type="text" size="15" value="Hello World" 开发者_如何学Cname="elmOne">
<input type="text" size="15" value="next Hello World" name="elmOne">
 <input type="button" onclick="javascript:validate()" value="validate">
</form> 


it is not a common practice to name two different text input element with a common name. However, back to the question, you can always use document.getElementByName('elmOne'); to get a list of the matching input, then loop through it for value

var input_list = document.getElementsByName('elmOne');

for(var i = 0; i < input_list.length; i++) {
    // either way should get you the value
    console.debug(input_list[i].value, input_list[i].getAttribute('value'));
}

you may want to refer to this page for further information on compatibility


you can use the document.forms property to get an array of document forms, starting from index 0 for the first form element appeared in HTML code, and so on. or you may access a form having a "name" attribute, by using the name as the array index. so to access the first form in your HTML code use:

var f = document.forms[0];

and if the form has the name like "loginForm", you may reach it like:

var f = document.forms['loginForm'];

now that you have a reference to the form, you can access elements in it using the .elements property of the form. this property is an array that has the same indexing properties like the document.forms. so you can access each for element by its order in HTML code using numerical indexes, 0 for the first, or use named indexes by placing each element's name attribute as the index.

so to access the second element in the form you may use:

var el = f.elements[1];

or if the element has the name attribute of "username", you can reference it by:

var el = f.elements["username"];

this way you can reference to any element in any form in your document.


var elem = document.form.all.namedItem("elmOne") will return array of required elements. Then just iterate through it and get values by using elem.value


var items = document.getElementsByName("elmOne");
for (var i = 0; i < items.length; i++) {
   var item = items[i];
}

However, this is going to have some unexpected behavior in IE. For more details, see this question. The basic idea is that Microsoft's implementation of this function is different than other browser's implementations. Therefore, you can get conflicting results across browsers.

The solution is to find a different way to associate those elements and use that to grab which items you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜