1

My function is the call that is made by the onchange event in an html select type input. I assign a variable that value, but it doesn't seem to get accessed by a variable of the same name outside that function, say, in $(document).ready()

<select form="submitForm" name="frequency" class="meal-type-select" onchange="getFreqVal(this)">
        <option value="O">One Time</option>
        <option value="D">Daily</option>
        <option value="W">Weekly</option>
        <option value="M">Monthly</option>
        <option value="Y">Yearly</option>
        <option value="R">Requested</option>
</select>

And the script is this: (There is a lot more to the script, but I've only shown the part relevant to the question, to make it less clattered)

<script>
$(document).ready(function() {

    var freqVal;


    $('#addPictures').click(function() {

        alert(freqVal);

    });

});

function getFreqVal(sel)
{
    freqVal =   sel.value;
    alert(freqVal);
}
</script>
1
  • Move the var freqVal; out of the document ready function.. to start of the script block.. Commented Jul 13, 2014 at 22:39

4 Answers 4

2

Just declare freqVal outside $(document).ready(). They're two different functions, essentially.

Sign up to request clarification or add additional context in comments.

2 Comments

Just fyi, by two different functions, I mean $(document).ready() and getFreqVal
Yes i understood that.
2

the variable freqval is outside the scope of getFeqVal(). This is what you should do:

<script>
    var freqVal;
    $(document).ready(function() {

        $('#addPictures').click(function() {

            alert(freqVal);

        });

    });

    function getFreqVal(sel)
    {
        freqVal =   sel.value;
        alert(freqVal);
    }
</script>

This makes the scope of freqVal global.

Comments

1

You are declaring your variable inside the function, so it won't be visible outside the function scope. The way you do it, both the functions have their own variable named freqVal.

You can use a global variable (member of window):

<script>

var freqVal; // here

$(document).ready(function() {
    $('#addPictures').click(function() {
        alert(freqVal);
    });
});

function getFreqVal(sel)
{
    freqVal = sel.value;
    alert(freqVal);
}

</script>

Comments

1

Remove the inline javascript and use jQuery

$(document).ready(function() {

    $('.meal-type-select').on('change', function() {

        // stuff on select change

    });

    $('#addPictures').on('click', function() {

        var freqVal = $('.meal-type-select').val();

    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.