最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS - Dynamically change Textfield - Stack Overflow

programmeradmin7浏览0评论

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

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

Share Improve this question asked Apr 16, 2012 at 15:53 Oliver JonesOliver Jones 1,4507 gold badges30 silver badges43 bronze badges 1
  • 1 Why has this been given a negative rating? Please ment here on whats wrong with my question, and I'll do my best to improve it. There's no point in giving negative rating and not bothering to leave feedback... It helps no one. – Oliver Jones Commented Apr 16, 2012 at 16:07
Add a ment  | 

4 Answers 4

Reset to default 6
<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/4PAKE/

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!

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

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

and then write the following code:

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

You can use jQuery to acplish 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.

发布评论

评论列表(0)

  1. 暂无评论