3gwebtrain
3gwebtrain

Reputation: 15299

How to avoid multiple event listeners on a text field?

I am making a application using Backbone Marionette. In which I need to observe and update the model on each of the text fields.

so, I used the following concept:

$("#textbox").on('keyup  paste focus focusout', function() {
    console.log('I am pretty sure the text box changed');
});

But the problem is, when a person paste some value to text box, I am getting the console 3 times or more. - how to suspend the 3 console? (it's all triggering same time keyup, focus, past)

Again is it good practice to use number of listener with a single text box? I am wondering the approach is correct or not about?

Is there any listener which taking care of anything happening with text box?

Or any good practice please?

using input as well make this type of issues too..

jQuery Input Event does not Fire if Input is Empty

Thanks In advance.

Here is the Live Demo

Upvotes: 1

Views: 600

Answers (4)

Jeetendra Chauhan
Jeetendra Chauhan

Reputation: 1977

you can listen any number of events with a single text box.

$("#textbox").on('keyup  paste focus focusout', function(e) {
    switch(e.type) {
        case  "keyup":
            console.log('keyup');        
        break;

        case  "paste":
            console.log('paste');        
        break;

        case  "focus":
            console.log('focus');        
        break;

        case  "focusout":
            console.log('focusout');        
        break;    
    }

});

DEMO

Upvotes: 3

Levent Çorapsız
Levent Çorapsız

Reputation: 163

for any property that changes on the #textbox element, not just the value property.

   jQuery('#textbox').on('input propertychange paste', function() {
        // do your stuff
    });

Upvotes: 0

mplungjan
mplungjan

Reputation: 178285

Are you asking the right question?

I think you are likely really asking

"How do I know if a field has changed" which is partly answered here: Get default value of an input using jQuery

The second part (the paste part) can be handled by adding the input event handler as answered by @shaunakde or if there is an issue, run a setInterval on focus and clearInterval on focusout

Upvotes: 0

Shaunak D
Shaunak D

Reputation: 20636

Here is an Updated Demo

$("#textbox").on('input focus focusout', function() {
    console.log('I am pretty sure the text box changed');
});
  • You can have a common input event instead of keyup and paste.
  • You can also implement change event, but it has some time lag before it is fired.

Input event Browser support

Upvotes: 0

Related Questions