Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
90
rated 0 times [  97] [ 7]  / answers: 1 / hits: 73339  / 13 Years ago, tue, april 5, 2011, 12:00:00

How can I set a Global Variable from within a function?



$(document).ready(function() {
var option = '';

$([name=select_option_selected]).change(function() {
var option = $(this).val();
alert(option); // Example: Foo
});

alert(option); // Need it to alert Foo from the above change function
});

More From » jquery

 Answers
24

Declare it outside the scope of your jQuery onready



var option = '';

$(document).ready(function() {
$([name=select_option_selected]).change(function() {
option = $(this).val();
alert(option); // Example: Foo
});

alert(option); //This will never be Foo since option isn't set until that select list changes
});


if you want to initialize this to the current selected value try this:



var option = ;
var $select_option_selected = null;

$(function() {
$select_option_selected = $([name='select_option_selected'])
$select_option_selected.change(function() {
option = $(this).val();
});
option = $select_option_selected.val();
});

[#92897] Sunday, April 3, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayaw

Total Points: 749
Total Questions: 88
Total Answers: 86

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
tayaw questions
;