Bruno Ghisi
Bruno Ghisi

Reputation: 1

Populate multiple fields with javascript

I am new to javascript and I can't populate many fields with one click.

<script>
  function addTxt(txt, field)
  {
      var myTxt = txt;
      var id = field;
      document.getElementById(id).value = myTxt;
  }
</script>

<input type="text" name="xx" id="info" autofocus="required">
<p><a  href="#" onclick="addTxt('x', 'info')">x</a></p>

I've got 3 more fields.

Thanks.

Upvotes: 0

Views: 1135

Answers (4)

user1710796
user1710796

Reputation:

Try getting the elements by tagName or by className instead of by id, then using a for loop to iterate through each one.

Upvotes: 0

Oriol
Oriol

Reputation: 288080

I think you don't need a function to do this.

Just use

document.getElementById('id1').value
    = document.getElementById('id2').value
    = document.getElementById('id3').value
    = 'Some text';

Or, if you think document.getElementById is too long, use a shortcut:

var get = document.getElementById;
/* ... */
get('id1').value = get('id2').value = get('id3').value = 'Some text';

Upvotes: 0

Abhinav015
Abhinav015

Reputation: 44

You can populate multiple fields. I have shared a jsfiddle link. You can populate multiple fields using this code.

function addTxt(_val, _id,_no)
  {

  var _myTxt = _val;
  var _id = _id;
  for(var i=1;i<=_no;i++){
    document.getElementById(_id+i).value = _myTxt;
  }

}

Click here to see DEMO

Upvotes: 0

Oriol
Oriol

Reputation: 288080

You can use

function addTxt(txt, ids)
{
    for (var i=0, l=ids.length; i<l; ++i) {
        document.getElementById(ids[i]).value = txt;
    }
}

And call it like

addTxt('Some text', ['id1', 'id2', 'id3']);

Upvotes: 2

Related Questions