Oliver Jones
Oliver Jones

Reputation: 1440

JS - Dynamically change Textfield

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

Upvotes: 4

Views: 32726

Answers (4)

Josh Farneman
Josh Farneman

Reputation: 1739

You can use jQuery to accomplish this as @sarwar026 mentioned but there are some problems with his answer. You can do it with jQuery with this code:

$('#textfield1').blur(function() { 
    $("#textfield2").val($("#textfield1").val());
}​);​

In order to use jQuery you'll need to include it on your page, before your script.

Upvotes: 0

sarwar026
sarwar026

Reputation: 3821

If you want to do it with jquery, then please add the following script

<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>

and then write the following code:

$("#textfield1").bind("input", function() {
    $("#textfield2").val($("#textfield1").text());
}

Upvotes: 1

Anish Gupta
Anish Gupta

Reputation: 2226

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!

Upvotes: 2

micha
micha

Reputation: 1085

<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/

Upvotes: 6

Related Questions