Reputation: 595
I have an event handler listening for a change in a dropdown and setting the value of a variable. I have declared the variable as global i.e. outside of any functions, and then set the value on change. However, once it has changed I need to be able to pick up the variable in other functions (not within the even handler). How can i 'extract' it from within the event handler? I've tried to return it but no luck - here is the code:
$(document).on('change', 'select#search_subject', function () {
if ($('#sBar3').show()) {
$('#sBar3').hide();
}
var subject = $('#search_subject>option:selected').text();
var id = $('#search_subject>option:selected').val();
ajaxSubject(subject, '#sBar3');
return subject;
});
console.log(subject);
the log just shows 'empty string' and I'm baffled. If possible I dont want to rejig the code to include everything within the event handler (there's lots of Google Map generating code in there and it will make for a pain) - i just need to get the subject variable out of the event handler if that makes sense - Thanks
Upvotes: 1
Views: 987
Reputation: 178011
If the select is not created later, then this would be simpler code after you remove the var
that makes subject local
$("#search_subject").on('change',function () {
$('#sBar3').toggle();
subject = $('option:selected',this).text();
var id = $(this).val(); // not used?
ajaxSubject(subject, '#sBar3');
window.console && console.log(subject);
return subject;
});
Upvotes: 0
Reputation: 639
By using the var
keyword, you're creating a new local variable, which you're then assigning the subject text to. If you've already defined subject
in the global scope, then your assignment line should simply be:
subject = $('#search_subject>option:selected').text();
Upvotes: 5