Passing data to a jQuery event handler

19,382

Solution 1

I modified the code in your jsFiddle. In jQuery, you can pass data as an argument and access it using event.data jQuery reference.

Solution 2

/*
 * I would not to referer UI elements here
 * Rather I would pass the $('#txtMessage').val() to the handler
 */

That is impossible.

If you want to use the current value of that input element then you have to access the UI element itself.

If your intent is to decouple the event handler from knowing which specific element is to be accessed, that's easily done by using event data to pass it to the handler, e.g.:

$(sel).on('click', {
   source: document.getElementById('txtMessage')
}, handler);

and the in the callback:

function handler(event) {
    var txt = event.data.source.value;
    ...
}

Note that the jQuery event data is supposed to be a map of key: value pairs as shown above. Passing in a jQuery object directly as shown in the accepted answer could easily break.

Share:
19,382
Alberto De Caro
Author by

Alberto De Caro

Software analyst and developer with 10 years of experience in web-based applications, multi-tier architectures, data integration. More then 3 years experience in web analytics, eCommerce, web tagging and implementation projects. Strong analytical and relationship attitudes. Good communication skills, always curious and learning oriented. Core technologies: Javascript, JSON, JQuery, AJAX HTML, CSS .NET technologies Web analytics: Adobe Analytics Adobe Dynamic Tag Manager (DTM) Systems and data integration: Sql Server SSIS XML Web Services

Updated on June 23, 2022

Comments

  • Alberto De Caro
    Alberto De Caro almost 2 years

    Scenario

    In a GUI, a user inserts some text in a text input and then clicks a button: inserted text will be displayed in a div.

    I have found a trivial solution (demo here), that is setting the output text inside the handler accessing the input element object. It sucks. Rather, I would pass the input text (not the element) to the handler.

    Question

    How can I pass parameters (the input message text in this case) to the handler function?