JS - Dynamically change Textfield

31,534

Solution 1

<form action="#" id="form_field">
   <input type="text" id="textfield1" value="" onKeyUp="document.getElementById('textfield2').value=this.value">
   <input type="text" id="textfield2" value="">
</form>

see it in action: http://jsfiddle.net/4PAKE/

Solution 2

You can do:

HTML:

<form action="#">
    <input type="text" id="field" value="" onChange="changeField()">
</form>

JS:

function changeField() {
    document.getElementById("field").value="whatever you want here";
}

Sometimes this won't work. So you need to use micha's solution:

<form action="#" id="form_field">
   <input type="text" id="textfield1" value="" onChange="document.getElementById('textfield2').value=this.value">
   <input type="text" id="textfield2" value="">
</form>

See this solution in this jsFiddle

You can read more about .value here.

Hope this helps!

Share:
31,534
Oliver Jones
Author by

Oliver Jones

Updated on April 17, 2020

Comments

  • Oliver Jones
    Oliver Jones about 4 years

    I'm trying to change the value in one textfield from the value of another textfield without any submits. Example:

    [Textfield 1 (type 'hello')]

    [Textfield 2 ('hello' is inserted here as well)]

    Below is my form:

    <form action="#" id="form_field">
       <input type="text" id="textfield1" value="">
       <input type="text" id="textfield2" value="">
    </form>
    

    I don't know much about JavaScript, is this even possible? Would appreciate any help.

    Thanks

  • j08691
    j08691 about 12 years
    Might want to note to the OP that you're solution requires jQuery.
  • Oliver Jones
    Oliver Jones about 12 years
    This works well, but it only changes the value after I click off the field. Is it possible to change the value in textfield 2 in real time? Thanks
  • micha
    micha about 12 years
    connect it to onKeyUp instead