Bwyss
Bwyss

Reputation: 1834

javascript how to dynamically update a variable

I have an html form that triggers a function to change a value, reference: http://jsfiddle.net/ZvuMh/3/ How can I use avalue dynamically in another function?

HTML:

<select id="sort_post_date">
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
    <option value="d">d</option>
    <option value="e">e</option>
    <option value="f">f</option>    
</select>​

Change value function:

    var avalue='';
function getSelectData(id) {


    // set value to be the current selected value
    avalue = jQuery(id+" option:selected").val();

    // change value whenever the box changes
    jQuery(id).change(function () {
        avalue = jQuery(id+" option:selected").val();
        console.log("I see a change! -> "+avalue);
    });

    console.log(avalue);
    return avalue;
}

var d = getSelectData("#sort_post_date");
console.log(d);​

Another function that wants to inherit avalue when function getSelectData changes it to another letter:

function somefunction(){
    var test = "foo"+avalue;
}

Upvotes: 1

Views: 1704

Answers (2)

bingjie2680
bingjie2680

Reputation: 7773

why not just call it directly like this, this way, the somefunction will be called every time the letter changes:

// change value whenever the box changes
jQuery(id).change(function () {
    avalue = jQuery(id+" option:selected").val();
    console.log("I see a change! -> "+avalue);
    somefunction(avalue);
});

function somefunction(avalue){
    var test = "foo"+avalue;
}

Upvotes: 2

Morgan Wilde
Morgan Wilde

Reputation: 17303

Use the global scope for that variable, like so window.avalue = 'value' and access it with window.avalue

Upvotes: 1

Related Questions