开发者

Update text on textarea value change w/ jQuery

I have a textarea. I need to update text in a div when a value in textarea is changed by either typing in it or by placing some value in it via another jQuery fun开发者_C百科ction or pasted.

$(document).ready(function(){
    function myFunc() {
        var input = $("#myTxt").val();
        $("#txtHere").text(input);
    }       
    myFunc();

    // EDIT BELOW -- this will update while typing
    $("#myTxt").keyup(myFunc);

});

<textarea id="myTxt"></textarea>
<div id="txtHere"></div>

It loads the value on page load but I'm not sure what to use to check for value in the textarea...


$(document).ready(function(){
    function myFunc(){
        var input = $("#myTxt").val();
        $("#txtHere").text(input);
    }       
    myFunc();

    //either this
    $('#myTxt').keyup(function(){
        $('#txtHere').html($(this).val());
    });

    //or this
    $('#myTxt').keyup(function(){
        myFunc();
    });

    //and this for good measure
    $('#myTxt').change(function(){
        myFunc(); //or direct assignment $('#txtHere').html($(this).val());
    });
});


For textarea, the .change function only gets called when the textarea looses focus.

I found my solution at this link: How can I bind to the change event of a textarea in jQuery?

$('#textareaID').bind('input propertychange', function() {
      $("#yourBtnID").hide();

      if(this.value.length){
        $("#yourBtnID").show();
      }
});

This worked perfectly for me. It handles any type of change, including pasting.

Plus this.value.length is a neat way of seeing if the textarea has been cleared.

Cheers!


$(document).ready(function(){
   $('#myTxt').keypress(function(e){
       $('#txthere').html($(this).val());
   });
});

This will do that.


You can use delegate event like this:

$('body').delegate('#myTxt', 'keyup change', function(){
   $('#txtHere').text(this.value);
});

This should update the text as soon as you type in the text box or paste.


2018, without JQUERY

The question is with JQuery, it's just FYI.

JS

let myTxt = document.getElementById('myTxt');
let txtHere = document.getElementById('txtHere');
myTxt.addEventListener('input', function() {
    txtHere.innerHTML = myTxt.value;
});

HTML

<textarea id="myTxt"></textarea>
<div id="txtHere"></div>


Use the change event handler (will activate when the content is changed and the textarea loses focus):

$('#myTxt').change(function(){
    var input = $("#myTxt").val();
    $("#txtHere").text(input );
});


$(document).delegate('#myTextareaId','input', function() {
  $('#myTextId').html($(this).val());
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜