1

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

7
  • 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. Commented May 31, 2013 at 20:07
  • thanks for helping a total noob understand a little more felix - cheers Commented May 31, 2013 at 20:12
  • subject=$("option:selected",this).text(); Commented May 31, 2013 at 20:16
  • @mplungjan for that matter, var id = $(this).val(); Commented May 31, 2013 at 20:19
  • @Mathletics yes, as I posted in my answer :) Commented May 31, 2013 at 20:35

2 Answers 2

5

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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;
});

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.