JS - 动态更改Textfield

时间:2012-04-16 15:53:40

标签: javascript forms dynamic input

我正在尝试在没有任何提交的情况下从另一个文本字段的值更改一个文本字段中的值。例如:

[Textfield 1(类型'hello')]

[Textfield 2(此处也插入'hello')]

以下是我的表格:

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

我对JavaScript了解不多,这有可能吗?非常感谢任何帮助。

由于

4 个答案:

答案 0 :(得分: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>

看到它的实际效果: http://jsfiddle.net/4PAKE/

答案 1 :(得分:2)

你可以这样做:

<强> HTML:

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

<强> JS:

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

有时这不起作用。所以你需要使用micha的解决方案:

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

请参阅此jsFiddle

中的此解决方案

您可以详细了解.value here

希望这有帮助!

答案 2 :(得分:0)

如果你想用jquery做,那么请添加以下脚本

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

然后编写以下代码:

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

答案 3 :(得分:0)

您可以使用jQuery来完成此操作,如@ sarwar026所述,但他的答案存在一些问题。您可以使用以下代码使用jQuery:

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

为了使用jQuery,您需要在脚本之前将其包含在页面上。

相关问题