Reputation: 1246
Any reason why the following code would not fire on keypress but would on page reload?
$(document).ready(function(){
$('#weight').keypress(valNum("weight", "weight"));
function valNum(number, clas){
var name = $("#"+number).val();
var reg = /^([0-9\-\ \.]{2,6})$/;
if(!reg.test(name)){
$("."+clas+" .nogood").show();
$("."+clas+" .good").hide();
}else{
$("."+clas+" .good").show();
$("."+clas+" .nogood").hide();
}
}
})
Upvotes: 0
Views: 550
Reputation: 17553
Like any other function or method, jQuery's .keypress()
method accepts an argument. This is where you pass the event handler function as an argument. What you're doing, however, is NOT passing the function valNum()
as an argument; you're actually executing the valNum()
function. Any time you see ()
after a function name, that executes the function. Instead, you just need to wrap the valNum()
function in an anonymous, non-executing function:
$('#weight').keypress(function(){
valNum("weight", "weight");
});
The syntax can obscure it, but the argument we're now passing to the .keypress()
method is:
function(){
valNum("weight", "weight");
}
This is the function that gets called when the keypress
event fires on the bound element. When this anonymous function is called, then it calls your valNum()
function.
This solves both of your issues: valNum()
will not be exected immediately, and instead it will run in response to the keypress
event.
Let me know if you have questions -- this is touching on some pretty important topics in JavaScript.
Upvotes: 1
Reputation: 38345
The problem you have is that you're not passing a function reference (as you thought), but rather the result of calling valNum("weight", "weight")
, to the .keypress()
function.
If you want to call an existing function with parameters, you'll need to wrap it in an anonymous function, like so:
$('#weight').keypress(function() {
valNum("weight", "weight");
});
Upvotes: 1
Reputation: 382696
Change:
$('#weight').keypress(valNum("weight", "weight"));
To:
$('#weight').keypress(function(){
valNum("weight", "weight");
});
With your previous statement, problem was that valNum
function was getting executed immediately because of ("weight", "weight")
. That's how you call a JS function immediately eg func()
. However, keyup
needs a callback function which is exactly what we have provided it with in latter case.
Upvotes: 2