Nick
Nick

Reputation: 16105

Access variables javascript/jquery

I have the following code

$('#first').click(function() {
    myVar = $(this).next().val();
});

$('#second').blur(function() {
    console.log(myVar);
});

How to access myVar within #second ?

Upvotes: 0

Views: 783

Answers (4)

user213154
user213154

Reputation:

The answers here are good. But I think you're at the point where you'd benefit from reading Crockford's JS slideshow. It's very good and explains several matters related to your question.

Upvotes: 0

Jonathon Bolster
Jonathon Bolster

Reputation: 15961

T.J. Crowder's answer does what you want. This is just an alternative (using the jQuery data storage methods):

$('#first').click(function() {
    // Assign this element to have data with the key 'myVar'
    $(this).data('myVar', $(this).next().val());
});

$('#second').blur(function() {
    // Read the data from the other element
    console.log($('#first').data('myVar'));
});

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075925

It depends on the wider context of your code. You can do this:

(function() {
    var myVar;

    $('#first').click(function() {
        myVar = $(this).next().val();
    });

    $('#second').blur(function() {
        console.log(myVar);
    });
})();

That creates an anonymous function and calls it right away. The purpose of the anonymous function is to provide a container for myVar without making myVar a global variable. Global variables are generally best avoided (not least because they become properties of the window object, which already has all sorts of junk stuck on it). Specifically, the functions you're assigning to your click and blur events become closures over the data inside the call to the anonymous function. They have access to myVar, but nothing else does. More here.

If your code is already inside a containing scope, or you don't care about adding to the global namespace, you don't need the anonymous function.

Upvotes: 5

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124888

Define myVar in the outer scope:

var myVar;

$('#first').click(function() {
    myVar = $(this).next().val();
});

$('#second').blur(function() {
    console.log(myVar);
});

Upvotes: 2

Related Questions