I have a form where some fields have the same element name. Is there a way to change the value of all the fields with the same name?
Asked
Active
Viewed 4.6k times
12
-
2Note: If they are radio buttons, they are supposed to have the same name. – Guffa Dec 11 '10 at 22:18
3 Answers
24
1) Use getElementsByName to put the elements in an array.
2) Loop over the array and set each element's value.
code:
var els=document.getElementsByName("yourElementNameHere");
for (var i=0;i<els.length;i++) {
els[i].value = "yourDesiredValueHere";}
If you only want to change the elements with that name in the form, use the form instead of document
, example: document.getElementById("yourFormID").getElementsByName(...)
-
2[`getElementsByName` seems not to be supported by IE or Opera!](http://www.quirksmode.org/dom/w3c_core.html#t125) – Felix Kling Dec 11 '10 at 22:22
-
@Felix Kling: that page reads "incomplete and incorrect" (against W3C DOM2 specs) yet it supported. – Free Consulting Dec 11 '10 at 22:40
-
-
@user205376: *Incomplete and incorrect* sounds very much like *don't use that method!* imo. – Felix Kling Dec 11 '10 at 22:54
-
@Felix Kling: check out what "incomplete and incorrect" means as outlined by PPK (this method is **very** old and was IE-specific before adoption by W3C :-) – Free Consulting Dec 11 '10 at 23:08
1
you can do more simple with JQUERY example :
html
<div id="form">
<input type="text" name="myinput" vale="yussan" />
</div>
js
var value = $('#form input[name=myinput]').val()

yussan
- 2,277
- 1
- 20
- 24
1
sample form
<form name="form1">
<input type="button" name="buttons" value="button1">
<input type="button" name="buttons" value="button2">
<input type="button" name="buttons" value="button3">
</form>
script
var form = document.form1; // form by name
var form = document.forms[0]; // same as above, first form in the document
var elements = form.buttons; // elements with same name attribute become a HTMLCollection
for (var i=0; i<elements.length; i++)
elements[i].value = elements[i].value.replace("button", "buttoff");

Free Consulting
- 4,300
- 1
- 29
- 50