Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Dynamic jQuery variable between same-page functions

Tags:

jquery

I've read several questions about using a variable in multiple functions by making it global (defining it outside of a funciton)... however, I have a function that produces a dynamic value on click (gets an href value of a link) -

I need to pass that resulting variable into another function.

Basically, I'm grabbing a clicked link's href value and then wanting to pass it to Ajax if a confirmation box is selected.

It doesn't seem that declaring the variable globally would work, as it's definition comes only if an onclick event is triggered.

Any thoughts?

like image 224
AshBrad Avatar asked May 03 '26 20:05

AshBrad


2 Answers

You can create the variable as a global with a value of null, and then set it in your first function. After you read the variable in your second function, set the value back to null.

Example:

var someGlobal = null;

function f1( ) {
    someGlobal = 'someValue';
}

function f2( ) {
    if( someGlobal == null ) {
        // the global isn't set! might want a message of some sort, or just ignore it
        return;
    }
    var myLocal = someGlobal;
    someGlobal = null;

    // do something with myLocal here
}
like image 177
kitti Avatar answered May 05 '26 09:05

kitti


Best way to achieve this is define the variable as you've read through outside sources outside of anything that is function(){}. What I usually do for my global variables for example is either set a default value or set it to a blank value above any of the other code I write in that JS.

Example:

var myHREFval;
$('a').click(function(){myHREFval = $(this).attr('href');});
like image 26
chris Avatar answered May 05 '26 08:05

chris