user3046608
user3046608

Reputation: 21

jquery .on() pass data through function

I am reading the .on() jquery documentation.

And is it possible to pass some data like this:

function greet( event ) {
 alert( "Hello " + event.data.name );
}
$( "button" ).on( "click", {name: "Karl"}, greet );

The prototype of the methos is:

$(selector).on(event,childSelector,data,function,map)

Is it possible to have a more complex thin instead of only a string into the data parameter?.

In my case: I will be generating dynamically some popups with a number input inside and some text.

Is it possible to capture the information inside the caller popup, i.e. the number and the text of the caller popup. Maybe something like this:

$(document).on('click', '#id', 
var data =[
var number = functionThatGetTheNumberOfThePopup
var test = captureTextOfPopup
] , 
function(event){
//use number
//use test
});

Upvotes: 2

Views: 5222

Answers (2)

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14892

Yes, you can pass arbitrary data. You do it in the form of an object:

$(document).on('click', '#id', {
        number: functionThatGetTheNumberOfThePopup,
        test: captureTextOfPopup
    },
    function(event){
    //use number
    console.log(event.data.number);
    //use test
    console.log(event.data.test);
});

Upvotes: 2

Jamiec
Jamiec

Reputation: 136154

You're example does pass something more complex than a "simple string" - you're example passes an object with one property name - there's no reason this couldnt be an object with 2 (or more) properties:

$(document).on('click', '#id', 
{
    number : functionThatGetTheNumberOfThePopup(),
    test : captureTextOfPopup()
} , 
function(event){
//use number
//use test
});

Upvotes: 0

Related Questions