Christian Christian - 2 months ago 7
Ajax Question

How can I pass a variable inside a event handler to another event handler with jQuery?

how can i pass a variable inside a event handler to another event handler

$("#vaccines").find("a").click(function() {
var sendvaccineval = $(this).attr('id');
});

$("#options").find("a").click(function() {
var sendbuttonval = $(this).attr('id');
});


I'm planning to use the attribute of the first event handler to the second one

I have two modals so theres a modal inside a modal, in the second modal i need to use the attribute of the first modal

Answer

If you need to execute common code between two event handlers, pass the parameter to a third function that has the common code.

$("#vaccines").find("a").click(function() {
    var sendvaccineval = $(this).attr('id');
    doSomething(sendvaccineval);
});

$("#options").find("a").click(function() {
    var sendbuttonval = $(this).attr('id');
    doSomething(sendbuttonval);
});

function doSomething(myButton)
{
    // ....  do something with the button...
}

And avoid globals unless they are really necessary, which I seriously doubt they are in this case

Comments