JavaScript更改字段名称的值
问题描述:
我有一个表单,其中某些字段具有相同的元素名称。有没有办法更改具有相同名称的所有字段的值?
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?
答
1)使用 getElementsByName 将元素放入数组中。
2)在数组上循环并设置每个元素的值。
1) Use getElementsByName to put the elements in an array.
2) Loop over the array and set each element's value.
代码:
var els=document.getElementsByName("yourElementNameHere");
for (var i=0;i<els.length;i++) {
els[i].value = "yourDesiredValueHere";}
如果只想更改表单中具有该名称的元素,请使用表单而不是 document
,示例: document.getElementById( yourFormID)。getElementsByName(...)
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(...)