views:

433

answers:

2

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.");
    }
+2  A: 

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. =)

Brian Arnold
Thanks Brian. This worked great!
Hcabnettek
Technically, the reason it is executing is because you were passing in a function call when jQuery callbacks request a function pointer- which is why the anonymous function works.
Nic
A: 

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];
}
camwest
cool, I will give this a try. Looks like the proper way to do it. Thanks!
Hcabnettek
No problem. The anonymous function is probably the simpler way to do it if you're using the procedure anywhere else though.
camwest