Set input value from current input textfield on change event

戏子无情 提交于 2020-01-24 09:56:45

问题


I have a table with two input boxes. A and B. I enter something into input A (and also B) and I want it's value to automatically be set to whatever I type into it on change event. Is this easy to do?

<tr>    
 <td><input type="text" id="A1" name="A" value=""></td>
 <td><input type="text" id="B1" name="B" value=""></td>
</tr>

回答1:


Description

If you want to keep the two input elements in sync on every keystroke you should use jQuery´s .keyup() and .change() (for copy and paste) method.

Sample

$("#A1").change(function() {
    $("#B1").val($("#A1").val());
});

$("#B1").change(function() {
    $("#A1").val($("#B1").val());
});

$("#A1").keyup(function() {
    $("#B1").val($("#A1").val());
});

$("#B1").keyup(function() {
    $("#A1").val($("#B1").val());
});

jsFiddle Demonstration

More Information

  • jQuery Documentation - .keyUp()
  • jQuery Documentation - .change()



回答2:


Try this:

$("#B1").bind("change keyup", function(){
    $("#B2").val($(this).val());
});

$("#B2").bind("change keyup", function(){
    $("#B1").val($(this).val());
});

This way it will pick up each character and will also get copy-and-paste text using the mouse.




回答3:


you can try something like this

$('#A1').change(function(){
  $('#B1').val($(this).val());
});

same for the other input

$('#B1').change(function(){
  $('#A1').val($(this).val());
});



回答4:


Change event for input[type=text] do not work as you would expect them to. It basically checks for the changed value of focus out and then fire the event.

I would recommend using keyup event to copy the value accross. it will be as simple as:

$('#A1').keyup(function(){
   $('#B1').val($('#A1').val());
});


来源:https://stackoverflow.com/questions/8674878/set-input-value-from-current-input-textfield-on-change-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!