开发者

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 fiel开发者_StackOverflowds with the same name?


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


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/


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜