0

I'm trying to return and access the value of a dynamic select from onchange event. I know how to work with function declarations but function expressions are unclear to me. A little help would be appreciated.

js

//create select
var select = document.createElement('select');
select.setAttribute('id','select_month');
//onchange
select.onchange = function changeMonth(selectedmonth){
selectedmonth = this.value;//works well here
return selectedmonth;
};

var selectedmonth = changeMonth();//undefined
Grogu
  • 2,097
  • 15
  • 36
  • 1
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+scope+of+named+function+expression) of [javascript named function expressions - scope accessibility](https://stackoverflow.com/q/17446646/4642212). – Sebastian Simon Jan 17 '21 at 21:03

1 Answers1

0

changeMonth is a variable that is scoped only to the function itself, and is therefore not available to the rest of the script.

Even if it was available, then realise that when that function is called by the DOM (when the event fires), it calls it with this bound to the DOM element. When you call it explicitly in your code, you should do the same.

The good thing is that the reference to the function is available as select.onchange, so use that. That way you solve both issues at the same time:

var selectedmonth = select.onchange(select);
trincot
  • 317,000
  • 35
  • 244
  • 286