1

I have 2 input in my form and I want it like this:

The value of the first input must be the value of the second input.

HTML

<input type="text" id="input1" onKeyUp="getVal()" name="" value="" />
<input type="text" id="input2" name="" value="" />

JAVASCRIPT

<script language="javascript" type="text/javascript">
  function getVal(){
  document.getElementById('input2').value = document.getElementById('input1').value;
  }
</script>

My current code is not working. Can somebody help?

2
  • 1
    Unrelated to your question, but both the language and type attributes on the script tag are superfluous. Commented Aug 13, 2015 at 6:58
  • Its typo you assigning blank value of input2 on keypup of input1. Commented Aug 13, 2015 at 7:01

4 Answers 4

1

This was backward, 1 was overwriting itself.

<script language="javascript" type="text/javascript">
    function getVal(){
        document.getElementById('input2').value = document.getElementById('input1').value;
    }
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

We know very well its not your question and your solution is perfect. But still we are voting to close question. Because OP is asking for just typo correction.
Oh that was just weird, with the other comment from someone else, I was just like woah what happened, no worries.
1

If you want to set the value on input2 to the value of input1 then you need to swap the ids.

<script language="javascript" type="text/javascript">
    function getVal(){
        document.getElementById('input2').value = document.getElementById('input1').value;
    }
</script>

Comments

1

You inverted you value attribution, meaning that each time you release a key in input1, the value of input1 is overwritter by input 2. Try this :

<script language="javascript" type="text/javascript">
  function getVal(){
      document.getElementById('input2').value = document.getElementById('input1').value;
  }
</script>

Comments

0

Using Javascript:

<script language="javascript" type="text/javascript">
  function getVal(){
  document.getElementById('input2').value = document.getElementById('input1').value;
  }
</script>

Using Jquery:

<script language="javascript" type="text/javascript">
  function getVal(){
  $("#input2").val($("#input1").val());
  }
</script>

By the way, why are you keeping the name as blank? I mean, name=""?

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.