简体   繁体   中英

Similar Jquery functions not firing keyup() more than once

I have a few Javascript functions that all look similar to me. but behave differently to how I want them to.

I would like another element to be updated with some text when the value of the input has been evaluated. However for code reuseability I would like to pass the element to be updated to the function, but when I do this the keyup() event will not fire when text is typed into the input box.

Why is this?

Here is the one that works, but I have so specify the element to be updated explicitly.

Keyup Working

$(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 on.

Keyup Not working

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 have also tried as arguments $(this) and "#inputfeedback" to no avail!

I have also tried to use classical Javascript function foo(bar){ ... } type functions but this has the same effect as the last example above.

I am sure it is something I am not doing right or understanding here but after a good few hours of searching and reading I can't find anything to help me with this one!

Thanks

You definitely can't do callbacks like that:

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

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'));
});

Try writing it this way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM