Reputation: 3854
Hi just wanted to know if this is a correct way. I know we can pass data using object notation and use it. But just wanted to know if the below code is correct. I am not sure about the below syntax.
function isValid(errMessage,errId,errClass){
alert();
if($("#"+errId).val()==""){
$("."+errClass).show();
$("."+errClass).html(errMessage);
return false;
}else{
$("."+errClass).hide();
}
}
$("#fname").on("blur",isValid("please enter first name","fname","ferror"));
I have seen syntax like below:
function test(){
alert("Hello World");
}
$("#fname").on("blur",test);
check this link for output http://jsfiddle.net/susheel61/M2jsX/
so just want to make clear if passing parameters directly works or not.
Upvotes: 0
Views: 87
Reputation: 34915
You can pass arguments to the event handler as a parameter to your event listener:
$("#fname").on("blur", {
msg: "please enter first name",
name: "fname",
error: "ferror"
}, isValid);
Then your isValid function can handle the data from the event object:
function isValid (event) {
var errMessage = event.data.msg,
errId = event.data.name,
errClass = event.data.error;
if ($("#"+errId).val()=="") {
$("."+errClass).show();
$("."+errClass).html(errMessage);
return false;
} else {
$("."+errClass).hide();
}
}
Upvotes: 1
Reputation: 68440
Your code call isValid
method and assign result as blur
handler so it's not exaclty right. You should do something like this
$("#fname").on("blur",function(){
isValid("please enter first name","fname","ferror")
});
It seems there are other improvements you could do. The most obvious for me is pass this.id
instead of harcoding the id
$("#fname").on("blur",function(){
isValid("please enter first name", this.id, "ferror")
});
Upvotes: 3