jQuery function bind on 'input propertychange&

2019-04-13 02:49发布

问题:

I have jQuery code that calls a function as such:

$('#text_area').bind('input propertychange', function() {...

The element being bound to the function is a text area. When I type and delete text the function gets called just fine, however when I select all of the text, either through a hot-key or dragging the mouse, and then hit backspace the function is not called. This is the only instance where I can not get the function to call. Is this expected with the 'input propertychange' event? If so how can I change this to work as expected? Note that this holds true for Chrome, IE, and Firefox.

回答1:

Would this suit your purposes?

$('#text_area').on('keyup', function() {
    console.log('called');
});

Fiddle: http://jsfiddle.net/KyleMuir/ruJZD/

Also, as of jQuery 1.7 .on() (http://api.jquery.com/on/) is the preferred way to bind events.

EDIT: since someone was after right click pasted text, here is an update:

$('#text_area').on('keyup paste', function() {
    console.log('called');
});

Fiddle: http://jsfiddle.net/KyleMuir/ruJZD/9/



回答2:

You need to call a function when your text area get cleared. Or you want to call the same function when text is pasted into the text area.

You can use the same code what you are included in your question. I have included a working demo with this answer

 <textarea id='textarea1'>data</textarea>

//....................

$("textarea").bind('input propertychange', function(){
  alert($(this).val());
});

Note: Use jquery plugin

DEMO

If you want to prevent simultaneous triggers then use the below code

<textarea id="textarea"></textarea>

//.......

var text = "";
$("#textarea").on("change keyup paste", function() {
    var Val = $(this).val();
    if(Val == text) {
        return; //prevent multiple simultaneous triggers
    }

    text = Val;

    alert("changed!");
});

DEMO1

'Note: Checked with chrome and firefox'


回答3:

.bind method has been deprecated latest 3 j query versions. instead on we can use .on in to get correct answer.

 <textarea id="anytextid"></textarea>
<div id="sethere"></div>

correct text for this change

$('#anytextid').on('input propertychange', function() {
    $('#sethere').html($(this).val().length );
});