Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
92
rated 0 times [  93] [ 1]  / answers: 1 / hits: 22636  / 11 Years ago, fri, may 3, 2013, 12:00:00

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.



Note: I have the same ID for all input boxes.



My code is given below



<!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>


Can anyone help?


More From » jquery

 Answers
8

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.



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>


Then, you can adapt your JavaScript accordingly.






jQuery



in jQuery, you could then set a value using:



$('.myids').val('value for all of them here');



jQuery jsFiddle here.






Pure JavaScript



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.


[#78452] Thursday, May 2, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kalias

Total Points: 79
Total Questions: 116
Total Answers: 116

Location: Malaysia
Member since Wed, May 11, 2022
2 Years ago
;