使用javascript为多个输入框分配值? [英] Assign value for multiple input boxes using javascript?
问题描述
我在将单个值分配给多个输入框时遇到问题.我正在尝试许多方法,但它只分配了1个文本框.如何分配多个文本框.
Hi I have a problem in assign single values to multiple input boxes. i am trying many ways but it assign only 1 text box. How can I assign multiple text boxes.
注意:我对所有输入框都有相同的ID.
Note: I have the same ID for all input boxes.
我的代码在下面给出
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
function getInputs()
{
var inputs = document.getElementsByTagName('input');
var ids = new Array();
for(var i = 0; i < inputs.length; i++)
{
if(inputs[i].getAttribute('id').toLowerCase()== 'myid')
{
document.getElementsById('myid').value="1";
}
}
}
window.onload = getInputs;
</script>
</head>
<body>
<form>
<input type="text" id="myid"><br>
<input type="text" id="myid"><br>
<input type="text" id="myid"><br>
<input type="text" id="myid"><br>
</form>
</body>
</html>
任何人都可以帮忙吗?
推荐答案
由于ID应该是唯一的,因此只为其中之一分配值;因此,您实际上只会最终以该值分配为目标.
It only assigns a value to one of because ID's should be unique; therefore you're only actually going to end up targetting the first one with that value assignment.
将HTML更改为使用类:
Change your HTML to use a class instead:
<input type="text" class="myids"><br>
<input type="text" class="myids"><br>
<input type="text" class="myids"><br>
<input type="text" class="myids"><br>
然后,您可以相应地修改JavaScript.
Then, you can adapt your JavaScript accordingly.
jQuery
在jQuery中,您可以使用以下方法设置值:
in jQuery, you could then set a value using:
$('.myids').val('所有这些值都在这里');
纯JavaScript
在Javascript中,您将使用 getElementsByClassName()
并对其进行迭代,从而为它们提供相同的值.
In Javascript, you'd use getElementsByClassName()
and iterate through them, giving them the same value.
var x = document.getElementsByClassName('myids');
for(i = 0; i < x.length; i++) {
x[i].value = "New!";
}
Pure JavaScript jsFiddle here.
这篇关于使用javascript为多个输入框分配值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!