How can I pass args to the event handler function? This runs the function on page load which is not the desired effect. I need this routine "validateText" to run against several different textbox, dropdown combinations. Can I reuse "validateText" instead of creating one per text/dropdown combination??
//add blur event handler to the textbox with jQuery when the page is finished loading
$(document).ready(function() {
$("#myTextbox").blur(validateText($("#myTextbox"), $("#Select1")));
})
function validateText(textbox, dropdown) {
var message = $("#message");
var isValid = false;
//get the value the user type in
var textboxValue = $(textbox).val();
//get the options from the lookup
var options = $("option", dropdown);
//loop through the options and compare it to "value"
options.each(function() {
var optValue = $(this).val();
if (optValue === textboxValue) {
isValid = true;
}
});
if (!isValid)
message.text(textboxValue + " is not a valid value from the list.");
else
message.text(textboxValue + " is perfectly valid.");
}
If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.
In your functions add a parameter called e.g. element and replace $(this) with element . Calling the function you have to add the parameter $(this) . $(date_field). click(function() { clearFmt($(this), date_fmt); });
Commonly Used jQuery Event Methods The click() method attaches an event handler function to an HTML element. The function is executed when the user clicks on the HTML element.
The this Keyword is a reference to DOM elements of invocation. We can call all DOM methods on it. $() is a jQuery constructor and in $(this), we are just passing this as a parameter so that we can use the jQuery function and methods.
Use binding to pass extra parameters to an event listener:
http://docs.jquery.com/Events/bind
$(document).ready(function() {
$("#myTextbox").bind("blur", [ $("#myTextBox"), $("#Select1")], validateText);
})
Then access the data from event.data:
function validateText(event) {
textBox = event.data[0];
dropdown = event.data[1];
}
The reason it calls at load is because handing over a function name with arguments actively calls it. You can effectively mimic what you're looking for by wrapping the call to validateText in an anonymous function like so.
$(document).ready(function() {
$("#myTextbox").blur(function(){
// Since in your original example you used $("#myTextbox") as an arg, this mimics it
validateText($(this), $("#Select1"));
});
});
The anonymous function, since it's using the 'this' keyword, should scale a little better with your initial selector if you change it from #myTextbox to textarea or whatever. =)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With