It is because the the change() handler will get executed only when the change event is fired from the select element. You are using the console.log() statement in a sequential executio which will get executed before the change handler is fired
//this is correct
var selectee = "JK";
//this registers a change handler for the select element
$('select.form-control.bfh-states').change(function () {
//but this will not execute now!!! it will get executed only when the select elements change event is fired
selectee = $(this).val();
console.log(selectee); // works correctly, but i need to access it outside the function
});
//this will get executed as soon as the change handler is registered not after the handler is executed
console.log(selectee);
If you want selectee to have the value selected in the select element then you can either do something like
var selectee = $('select.form-control.bfh-states').val() || "JK";
or manually fire the select change handler once the handler is attached on dom ready like
var selectee = "JK";
$('select.form-control.bfh-states').change(function () {
selectee = $(this).val();
console.log(selectee); // works correctly, but i need to access it outside the function
}).change();
$('select option:selected').val();can simply bethis.value.