Iterating through same form elements

强颜欢笑 提交于 2019-12-22 12:41:30

问题


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" name="elmOne">
<input type="text" size="15" value="next Hello World" name="elmOne">
 <input type="button" onclick="javascript:validate()" value="validate">
</form> 

Thanks..


回答1:


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




回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/2505786/iterating-through-same-form-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!