简体   繁体   中英

Extracting variable from onchange event handler for use in other functions

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 ie 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM