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);
});