JQuery.on keyup and blur only on boot

Problem: keyup and keyup , each of which is fired once at boot and only loads. How can I make them work correctly?

JQuery:

 function myFunction(text){ alert(text); } $('#input1').on({ keyup: myFunction('keyup'), blur: myFunction('blur'), focus: function(){console.log('focus!');} }); 

Fiddle: http://jsfiddle.net/GrMQX/

+7
source share
5 answers

You do not assign a keyup and blur function, you assign a result to myFunction .

Change it like this:

 $('#input1').on({ keyup: function() { myFunction('keyup'); }, blur: function() { myFunction('blur'); }, focus: function() { console.log('focus!'); } }); 

Demo

+13
source

You do not declare functions as callbacks, you execute them, and their return result is assigned as a callback (which does not work).

Try the following:

  $('#input1').on({ keyup: function() { myFunction('keyup') }, blur: function() { myFunction('blur') }, focus: function(){console.log('focus!');} }); 
+6
source

You need to pass the function as an argument. You pass the return value of the called function

 function myFunction(text){ alert(text); } $('#input1').on({ keyup: function(){myFunction('keyup');}, blur: function(){myFunction('blur');}, focus: function(){console.log('focus!');} }); 

Or you can convert myFunction to a function generator

 function myFunction(text){ return function(){ console.log(text); } } $('#input1').on({ keyup: myFunction('keyup'), blur: myFunction('blur'), focus: function(){console.log('focus!');} }); 

Demo at http://jsfiddle.net/gaby/GrMQX/6/

+6
source

In fact, you execute functions when you call them that way. Try the following:

 $('#input1').on({ keyup: function(){myFunction('keyup')}, blur: function(){myFunction('blur')}, focus: function(){console.log('focus!');} }); 

JsFiddle example

+4
source

use with .on () event

 $(document).on("keyup blur", "#input1", function(event) { // your code }); 
0
source

All Articles