开发者

How to have multiple input boxes of the same name on a page?

I am making a web page. It has some input fields grouped into one section, and then below that section is an "Add another" button. That button will add another identical section to the page using JavaScript; the same form fields.

Then later down the page there is a "Calculate" button. It run开发者_开发知识库s some other JavaScript which needs to have access to these input fields via jQuery.

What is the recommended way to have multiple duplicate input elements on the page? I am aware that there shouldn't be two elements with the same ID, but what happens with two elements of the same name? Can they be accessed individually? Or should I name these input elements differently with JavaScript, e.g. adding a "1", "2", etc. to the end of their name, and then use loops? (that seems messy)

How should I identify and access these identical groups of input fields?


You can use the document.getElementsByName('name') and then loop over the result to get each value.


As long as they have differents ids they can have the same name without trouble.

When you submit them, the server will get repeated name/value pairs and needs to be aware of that in processing them. Different languages differ in how they do that, you'll have to consult appropriate documentation for how to do it with whatever you are using.


What is the recommended way to have multiple duplicate input elements on the page?

Just do it.

I am aware that there shouldn't be two elements with the same ID, but what happens with two elements of the same name?

Any methods available to JS for accessing them by name will give you a collection instead of an element. You can access the individual elements within just like an array (including looping over with for and collection.length).

Can they be accessed individually?

If you are accessing them by name, then you can use their index. (collection[0]).

You can also give them ids if you want to access a specific one.

If you want to link elements together and have them refer to each other, then you can use the DOM structure to help you.

For a very simplified example:

<div>
    <input>
    <button onclick="alert(this.parentNode.getElementsByTagName('input')[0]);">...</button>
</div>

Obviously, in a real world situation you should use unobtrusive JS and build on things that work.


You can give the name as an array
ex:

<input type="text" name="textBox[]"/>

You can append the same form on clicking "Add Another" Button. You can access them using textBox[0], textBox[1] etc.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜