KTDPMH
KTDPMH

Reputation: 31

keypresss event automatically fires after text input loses focus and gained focus again

The script is used to writes down to console the input of users. Everything goes well if it is the first time the text input gains focus. But once the input loses focus and gains focus again, it doubling the characters I type in the input. I tracked and saw that though I only tap 1 time, the function autocomplete() was called two time. So, what happens here?

Update: the more times the input loses and gains focus again, the more times the method is automatically called!

var userInput = ''; //store input of users
var $userInput = $('#userInput'); // text input element

$userInput.on('focus', function(){
    console.log('gain focus');
    var matchedArray = [];
    init($userInput, matchedArray);

});

function init($el, matchedArray){
    $el.on('keypress', function(event){
        autoComplete(event);        
    });

    function autoComplete(evt){ 
        if(evt.which !== 8){ 
            userInput += String.fromCharCode(evt.which);
            console.log(userInput); 
        }else{
            userInput = userInput.slice(0, userInput.length - 1);
            console.log('after backspace: '+userInput);         
        }
    }


}

Upvotes: 0

Views: 48

Answers (1)

Brennan
Brennan

Reputation: 5732

You are binding the same handler multiple times, without ever having unbound it. Every time you focus on the field, you are adding an additional autoComplete(event) call. You need to call .off() on the keypress when the blur event fires for that field.

$userInput.on('focus', function(){
    console.log('gain focus');
    var matchedArray = [];
    init($userInput, matchedArray);
});

function init($el, matchedArray){
    var handler = function(event) {
        autoComplete(event);
    }        
    $el.on('keypress', handler);

    $el.on('blur', function() {
      $el.off('keypress', handler);
    });

    function autoComplete(evt){ 
        if(evt.which !== 8){ 
            userInput += String.fromCharCode(evt.which);
            console.log(userInput); 
        }else{
            userInput = userInput.slice(0, userInput.length - 1);
            console.log('after backspace: '+userInput);         
        }
    }
}

Upvotes: 2

Related Questions