Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a Global Variable from within a function

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    
});
like image 868
Phill Pafford Avatar asked Apr 05 '11 18:04

Phill Pafford


People also ask

Can global variables be altered inside functions?

Such variables are said to have local 'scope'. Functions can access global variables and modify them. Modifying global variables in a function is considered poor programming practice. It is better to send a variable in as a parameter (or have it be returned in the 'return' statement).

Can you assign a variable within a function?

You can assign global variables from inside the function using "<<-" operator.

How do you declare a global variable inside a function in Java?

To define a Global variable in java, the keyword static is used. Java actually doesn't have the concept of Global variable, it is known as class variable ( static field ). These are the variables that can be used by the entire class.


1 Answers

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();
});
like image 141
hunter Avatar answered Oct 08 '22 23:10

hunter