Hcabnettek
Hcabnettek

Reputation: 12928

How can I pass args to event handler?

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.");
    }

Upvotes: 7

Views: 11363

Answers (2)

camwest
camwest

Reputation: 312

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];
}

Upvotes: 11

Brian Arnold Sinclair
Brian Arnold Sinclair

Reputation: 3833

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

Upvotes: 5

Related Questions