jQuerybeast jQuerybeast - 6 months ago 47
jQuery Question

jQuery Global Variable

Can someone explain me why this doesn't work:

$(function() {
var damg = $(".hidden").val();

$("button").click(function() {
alert(damg);
});
});


jsFiddle: http://jsfiddle.net/raFnT/

Is it good to use global variables? I've also read that it is a slower option than typing it every time?

To explain in detail:

I have this:

$("button").click(function() {
alert(damg);
});


and the damg is a value of the input:
var damg = $(".hidden").val();


When you type something in the input and THEN press the button, alert the value of that input.

I could use

$("button").click(function() {
var damg = $(".hidden").val();
alert(damg);
});


but in one point that I will have 100 functions I will end up like this:

$("button1").click(function() {
var damg = $(".hidden").val();
alert(damg);
});

$("button2").click(function() {
var damg = $(".hidden").val();
alert(damg);
});

$("button3").click(function() {
var damg = $(".hidden").val();
alert(damg);
});

$("button4").click(function() {
var damg = $(".hidden").val();
alert(damg);
});

$("button5").click(function() {
var damg = $(".hidden").val();
alert(damg);
});


I want to set a global variable so that on every function I don't need to call the function again.

Something like this:

var damg = $(".hidden").val();

$("button1").click(function() {
alert(damg);
});

$("button2").click(function() {
alert(damg);
});

$("button3").click(function() {
alert(damg);
});

$("button").click(function() {
alert(damg);
});

$("button4").click(function() {
alert(damg);
});

$("button5").click(function() {
alert(damg);
});

BNL BNL
Answer

You have it backwards, a global variable has to be written OUTSIDE of a function.

Your code doesn't work because .hidden doesn't have a value.

http://jsfiddle.net/raFnT/2/

It is bad practice to use global variables unless you really need them to be global. I don't know what you mean by 'typing it every time.'

Also, you are not reloading the value in the click handler.

$(function() {            
    $("button").click(function() {
        var damg = $(".hidden").val();
        alert(damg);
    });            
});

http://jsfiddle.net/raFnT/6/

In the interest of having a good answer, what the OP wants is the blur function.

$(function() {     
    var damg;

    $(".hidden").blur(function () {
        damg = $(".hidden").val();
    });

    $("button").click(function() {
        alert(damg);
    });            
});

http://jsfiddle.net/raFnT/7/