Javascript 根据另一个填充 1 个表单字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2004315/
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-22 22:21:12  来源:igfitidea点击:

Populate 1 form field based on another

javascriptjqueryforms

提问by Hymanson

Is there an easy way to populate one form field with duplicate content from another form field?

有没有一种简单的方法可以用另一个表单域中的重复内容填充一个表单域?

Maybe using jQuery or javascript?

也许使用 jQuery 或 javascript?

回答by CMS

You just have to assign the field values:

您只需要分配字段值:

// plain JavaScript
var first = document.getElementById('firstFieldId'),
    second = document.getElementById('secondFieldId');

second.value = first.value;

// Using jQuery
$('#secondFieldId').val($('#firstFieldId').val());

And if you want to update the content of the second field live, you could use the changeor keyupevents to update the second field:

如果你想更新第二个字段的内容live,你可以使用changeorkeyup事件来更新第二个字段:

first.onkeyup = function () { // or first.onchange
  second.value = first.value;
};

With jQuery:

使用 jQuery:

$('#firstFieldId').keyup(function () {
  $('#secondFieldId').val(this.value);
});

Check a simple example here.

在此处查看一个简单示例。

回答by Kshitij Saxena -KJ-

In Native Javascript:

在原生 Javascript 中:

var v1 = document.getElementById('source').value;
document.getElementById('dest').value = v1;

回答by Antonin Hildebrand

It is easy in javascript using jQuery:

使用 jQuery 在 javascript 中很容易:

$('#dest').val($('#source').val());