jquery更改2输入文本字段的值

时间:2021-12-19 09:50:34

I want to create 2 text fields which will change at same time

我想创建2个文本字段,这些字段将同时更改

<input type="text" class="text1">
<input type="text" class="text2">

They are created dynamically, so my code is:

它们是动态创建的,所以我的代码是:

$("body").on("keyup", function() {
    $(".text2").val($('.text1').val());
});

It works only when changing text1. How can I write my script so I could change text2 too?

它仅在更改text1时有效。如何编写脚本以便我也可以更改text2?

Thank you!

2 个解决方案

#1


6  

You can do something like

你可以做点什么

var $ins = $('.text1, .text2').keyup(function() {
  $ins.not(this).val(this.value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="text1">
<input type="text" class="text2">

Here we change the value of input field other than the one in which the keyup is done to the updated value.

在这里,我们将输入字段的值更改为更新值以外的输入字段的值。


Using event delegation

使用事件委托

$(document).on('keyup', '.text1, .text2', function() {
  $('.text1, .text2').not(this).val(this.value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="text1">
<input type="text" class="text2">

#2


0  

you can try this

你可以试试这个

$("body").on("keyup", function() {
    var val1=$('.text1').attr('value');
    $(".text2").attr('value',val1);
});

#1


6  

You can do something like

你可以做点什么

var $ins = $('.text1, .text2').keyup(function() {
  $ins.not(this).val(this.value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="text1">
<input type="text" class="text2">

Here we change the value of input field other than the one in which the keyup is done to the updated value.

在这里,我们将输入字段的值更改为更新值以外的输入字段的值。


Using event delegation

使用事件委托

$(document).on('keyup', '.text1, .text2', function() {
  $('.text1, .text2').not(this).val(this.value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="text1">
<input type="text" class="text2">

#2


0  

you can try this

你可以试试这个

$("body").on("keyup", function() {
    var val1=$('.text1').attr('value');
    $(".text2").attr('value',val1);
});