Append INPUT to TEXTAREA as being typed in JQuery

时光总嘲笑我的痴心妄想 提交于 2019-12-12 17:02:20

问题


I have an INPUT text box.

As someone types into the INPUT text box, i need it to append/add-to a TEXTAREA value.


Lets say user types '12345' into the text box.

The textarea (default value="Comment: ") will automatically add: 'Comment: 12345'. Adding '12345' as they type.


回答1:


Assuming area is the id of your textarea and text the id of your textbox,

$(function() {

  var areaText = $('#area').val();  

  $('#text').bind('keyup keypress', function() { 
      $('#area')[0].value = areaText + $(this)[0].value;
  });

});
  • Working Example here add /edit to the URL to play with the example



回答2:


Russ Cam is missing an edge case -- you can drag and drop text into and within input fields by highlighting and dragging, which his code does not account for.

Below code that covers this case:

$(function() {

  var areaText = $('#area').val();  

  $('#text').bind('keyup keypress drop', dropfunction() { 
      $('#area')[0].value = areaText + $(this)[0].value;
  });

});

That said, there is still another edge case, which is deleting and manipulating via context menu. As of right now I can't see a way to detect the selection of context menu interaction... You could disable it if that is important using the following code

$('#text').bind('contextmenu', function() { 
    return false
});



回答3:


$('#your_input').bind('keypress', function(event) { 
    var char_code = event.which ? event.which : window.event.keyCode;
    var char = String.fromCharCode(char_code);
    $('#your_textarea').value += char;
});


来源:https://stackoverflow.com/questions/913042/append-input-to-textarea-as-being-typed-in-jquery

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