Javascript JS - 动态更改文本字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10177487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:10:52  来源:igfitidea点击:

JS - Dynamically change Textfield

javascriptformsdynamicinput

提问by Oliver Jones

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

我正在尝试将一个文本字段中的值从另一个文本字段的值更改为没有任何提交。例子:

[Textfield 1 (type 'hello')]

[文本字段 1(输入“你好”)]

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

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

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.

我对 JavaScript 不太了解,这可能吗?将不胜感激任何帮助。

Thanks

谢谢

回答by micha

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

看看它在行动:http: //jsfiddle.net/4PAKE/

回答by Anish Gupta

You can do:

你可以做:

HTML:

HTML:

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

JS:

JS:

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

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

有时这行不通。所以你需要使用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>

See this solution in this jsFiddle

在此jsFiddle 中查看此解决方案

You can read more about .valuehere.

您可以.value在此处阅读更多信息。

Hope this helps!

希望这可以帮助!

回答by Josh Farneman

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

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

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

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

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

回答by sarwar026

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

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

<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());
}