最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - change textfield with every keyup - Stack Overflow

programmeradmin4浏览0评论

I'm trying to fill three fields with the same text but I'm only writing into the first one. This code is only working once and then it isn't (the alert is working fine constantly).

$( 'textarea[name="posting"]' ).on( "keyup", function() {
 var text = $('textarea[name="posting"]').val();
    $('textarea[name="posting_twitter"]').replaceWith(text);
      alert(text)
});

I'm trying to fill three fields with the same text but I'm only writing into the first one. This code is only working once and then it isn't (the alert is working fine constantly).

$( 'textarea[name="posting"]' ).on( "keyup", function() {
 var text = $('textarea[name="posting"]').val();
    $('textarea[name="posting_twitter"]').replaceWith(text);
      alert(text)
});
Share Improve this question edited Jun 22, 2015 at 15:16 j08691 208k32 gold badges269 silver badges280 bronze badges asked Jun 22, 2015 at 15:12 dk1990dk1990 3093 silver badges15 bronze badges 4
  • 3 Have you tried changing replaceWith(text) to val(text)? jsfiddle/j08691/ccp7eopf/1 – j08691 Commented Jun 22, 2015 at 15:15
  • 1 @j08691 - you are right – Sudharsan S Commented Jun 22, 2015 at 15:16
  • try adding event.preventDefault(); – Timotheus0106 Commented Jun 22, 2015 at 15:16
  • 1 j08691 is correct. When you use replaceWith(text) it is actually replacing the selected element(s) with that string rather than updating the value. – mason81 Commented Jun 22, 2015 at 15:19
Add a ment  | 

4 Answers 4

Reset to default 4

See the working jsfiddle:

JS:

$('#first').on('keyup', function() {
   $('#second').val($(this).val()); 
});

HTML:

<input id="first" type="text">
<input id="second" type="text">

All you need to do is use jQuery's .val() method, which can both set and get the value of an input element. Read the documentation.

Try this:

$( 'textarea[name="posting"]' ).on( "keyup", function() {

 var text = $('textarea[name="posting"]').val();
    $('textarea[name="posting_twitter"]').val(text);
      alert(text);

});

Text area value can be replaced with val()

  $('textarea[name="posting_twitter"]').val(text)

like this?

html

<textarea name = "posting"></textarea>
<textarea name = "posting_twitter"></textarea>

jquery

$('textarea[name="posting"]').on("keyup", function(){
    var text = $(this).val();
    $('textarea[name="posting_twitter"]').val(text);    
});
发布评论

评论列表(0)

  1. 暂无评论