Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript change fields value by name

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?

like image 888
user485659 Avatar asked Dec 11 '10 22:12

user485659


3 Answers

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()
like image 76
yussan Avatar answered Nov 09 '22 01:11

yussan


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

like image 44
Konerak Avatar answered Nov 09 '22 02:11

Konerak


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/

like image 1
Free Consulting Avatar answered Nov 09 '22 03:11

Free Consulting