jQuery save local variable for use later on in the code

52,560

Solution 1

try this:

jQuery(element).data(key,value);
// Store arbitrary data associated with the matched elements.

or declare your variable outside the function.

var example;

function abc(){
   example = "12345";
}

abc();

console.log(example);

Solution 2

var jdc;
var jdi;    

$( "#droppable2" ).droppable({
    activeClass: "ui-state-hover",
    hoverClass: "ui-state-active",
    accept: "#draggable3",
    drop: function( event, ui ) {

        jdc = $(this).attr("id"); //I need to use this value later
        $( this )
            .addClass( "ui-state-highlight" );
            var x = ui.helper.clone();   
            x.appendTo('body');

            jdi = $("img").attr("id");// I need to use this value later

            $(this).droppable( 'disable' );
    }
});

Solution 3

You could always just store them as data on the element:

$(this).data('jdi', $('img').attr('id'));

Then you can get it back from that element with another call to ".data()":

var theSavedJdi = $('whatever').data('jdi');
Share:
52,560
Sol
Author by

Sol

Updated on December 13, 2020

Comments

  • Sol
    Sol over 3 years

    Is there anyway that I can save or access a local variable outside of it's function? Consider the code below:

    $( "#droppable2" ).droppable({
            activeClass: "ui-state-hover",
            hoverClass: "ui-state-active",
            accept: "#draggable3",
            drop: function( event, ui ) {
    
                jdc = $(this).attr("id"); //I need to use this value later
                $( this )
                    .addClass( "ui-state-highlight" );
                    var x = ui.helper.clone();   
                    x.appendTo('body');
    
                    var jdi = $("img").attr("id");// I need to use this value later
    
                    $(this).droppable( 'disable' );
            }
        });
    

    Is there anyway to get the values of the two variables (jdc and jdi above) for later use outside of the function?

    The ultimate goal is to get id of droppable container and content of dropped element.

  • Sol
    Sol almost 13 years
    Thanks for the initiative Thomas; and Kei for the implementation. MASSIVE THANKS to everyone. Works like a charm. :D
  • Luke
    Luke over 9 years
    Just to be explicit (for any newbies out there - I am one and this is what I was doing wrong), declaring the variable (var example;) outside the function and defining the variable (example = "12345";) inside the function is the key to this answer. It won't work if you declare + define the variable (var example = "12345";) inside the function - this will only apply locally (inside the function). In short, to save a local variable globally, declare (use var) outside the function and define (don't use var) inside the function.