Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign value for multiple input boxes using javascript?

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?

like image 722
Padmanathan J Avatar asked May 03 '13 09:05

Padmanathan J


2 Answers

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.

like image 88
dsgriffin Avatar answered Sep 28 '22 23:09

dsgriffin


The id attribute is supposed to be unique so having the same id several times is invalid html and most browsers will simply ignore any inputs with ids that already exist int he dom tree.

Sidenote: To set the value of several ids (via jquery) use the val() function and a selector that selects all respective inputs like this (it looks alot more cleaner to have this in a one-liner as opposed to sticking to pure javascript):

$('#myid1, #myid2, .myclass1').val('new value');
like image 27
Gung Foo Avatar answered Sep 29 '22 01:09

Gung Foo