0

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.

5
  • If you're new, this is (sadly) going to get sorta complicated for you. Make it easier on yourself and replace the <a> with a <button> or somethin Commented Dec 28, 2013 at 23:26
  • @Deryck How can I do it with a <button> ? Commented Dec 28, 2013 at 23:30
  • 1
    The element used will have no impact on this whatsoever. Commented Dec 28, 2013 at 23:31
  • Your current function can be simplified to function addTxt(txt, id){ document.getElementById(id).value = txt; }. There's no need to copy arguments to new local variables. Commented Dec 28, 2013 at 23:33
  • 1
    @BrunoGhisi just replace your <a> with <button onclick="addTxt('x', 'info')" type="button">X</button> and you can format it to look like anything in the world with CSS Commented Dec 28, 2013 at 23:38

4 Answers 4

2

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']);
Sign up to request clarification or add additional context in comments.

Comments

0

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

4 Comments

Why do all variables begin with _?
I have updated my code on jsfiddle. Now you can populate multiple data using this code.Please check it out. Click here DEMO
We can you _ in variables or identifiers.
Its ok. Can you please increase my reputation or vote. So that i would be solving problems more efficiently
0

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';

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.