12

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?

Konerak
  • 39,272
  • 12
  • 98
  • 118
user485659
  • 689
  • 4
  • 12
  • 20

3 Answers3

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(...)

frnhr
  • 12,354
  • 9
  • 63
  • 90
Konerak
  • 39,272
  • 12
  • 98
  • 118
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");

http://jsfiddle.net/yGV3R/

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