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

share|improve this question
4  
You said you declared the variable in global scope. Then don't declare a local variable with the same name, omit var. Of course the console.log(subject); will still show undefined since the event hasn't happened yet at the moment the statement is executed. – Felix Kling May 31 '13 at 20:07
    
thanks for helping a total noob understand a little more felix - cheers – Mobaz May 31 '13 at 20:12
    
subject=$("option:selected",this).text(); – mplungjan May 31 '13 at 20:16
    
@mplungjan for that matter, var id = $(this).val(); – Mathletics May 31 '13 at 20:19
    
@Mathletics yes, as I posted in my answer :) – mplungjan May 31 '13 at 20:35
up vote 5 down vote accepted

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();
share|improve this answer

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;
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.