Javascript Javascript按名称更改字段值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4419232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:20:23  来源:igfitidea点击:

Javascript change fields value by name

javascripthtmlformsdom

提问by user485659

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?

我有一个表单,其中某些字段具有相同的元素名称。有没有办法更改所有同名字段的值?

回答by Konerak

1) Use getElementsByNameto put the elements in an array.
2) Loop over the array and set each element's value.

1) 使用getElementsByName将元素放入数组中。
2) 遍历数组并设置每个元素的值。

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

如果您只想更改表单中具有该名称的元素,请使用表单而不是document,例如:document.getElementById("yourFormID").getElementsByName(...)

回答by Free Consulting

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/

http://jsfiddle.net/yGV3R/

回答by yussan

you can do more simple with JQUERY example :

您可以使用 JQUERY 示例做更简单的事情:

html

html

<div id="form">
<input type="text" name="myinput" vale="yussan" />
</div>

js

js

var value = $('#form input[name=myinput]').val()