Similar jQuery functions do not run keyup () more than once

I have several Javascript functions that are similar to me. but behave differently as I want them.

I would like another element to be updated with some text when the input value has been evaluated. However, to reuse the code, I would like to pass an element that will be updated for the function, but when I do this, the keyup() event will not fire when the text is entered in the input field.

Why is this?

Here is the one that works, but I specified the element that needs to be updated explicitly.

Work with keys

 $(function(){ $("#form1").keyup(function(){ var val = $(this).val(); if(val.length < 5){ $("#inputFeedback").html("Less then 5 chars"); }else{ $("#inputFeedback").html("More then 5 Chars!"); } }); 

Here is what I would like to do, but the keyup() event will not work.

Key does not work

 var validate = function(feedback){ var val = $(this).val(); if(val.length < 5){ $(feedback).html("Less then 5 chars"); }else{ $(feedback).html("More then 5 Chars!"); } } $(function(){ $("#form1").keyup(validate($("#inputFeedback"))); }); 

Note: I also tried both the $(this) and "#inputfeedback" no avail!

I also tried to use classic functions like Javascript function foo(bar){ ... } , but this has the same effect as the previous example above.

I am sure that this is something that I am not doing right or do not understand here, but after several hours of searching and reading I can not find anything to help me with this!

thanks

+4
source share
3 answers

You definitely cannot make such callbacks:

http://docs.jquery.com/How_jQuery_Works#Wrong

+1
source
 var validate = function(feedback){ var val = $(this).val(); if(val.length < 5){ $(feedback).html("Less then 5 chars"); }else{ $(feedback).html("More then 5 Chars!"); } } $(function(){ $("#form1").keyup(function(){ validate.call(this, '#inputFeedback'); }); }); 

or

 var validate = function(feedback){ return function(){ var val = $(this).val(); if(val.length < 5){ $(feedback).html("Less then 5 chars"); }else{ $(feedback).html("More then 5 Chars!"); } } } $(function(){ $("#form1").keyup(validate('#inputFeedback')); }); 
+1
source

Try to write it like this:

 var feedback=$("#inputFeedback"); $("#form1").keyup(validate(feedback)); 
0
source

All Articles