0

I have a functions that looks like this:

foo = document.getElementById("something"); 

foo.addEventListener('change',  function(e){
    value = this[this.selectedIndex].text
    id    = this[this.selectedIndex].value
}, false);


alert(value) // nothing

Is there any way to get value and id out of the functions scope?

meskerem
  • 349
  • 1
  • 7
  • 15

3 Answers3

2

Does it help? After you change the drop-down option, you can pass the value to a callback function. The reason you would get event handler's values is because you would assign them inside the event handler but declare them outside the handler. See the example below:

foo = document.getElementById("something"); 
var value, id;

foo.addEventListener('change',  function(e){
    value = this[this.selectedIndex].text;
    id    = this[this.selectedIndex].value;
    callBack();
}, false);

function callBack() {
   alert(value);
}
<select id="something">
 <option value="1">One</option>
 <option value="2">Two</option>
</select>

The reason you were not getting the value in your code was that the event handler code was being executed later on change event. However, at that time alert code was not getting executed. Note that variables declared in outer scopes can be accessed inside inner scopes but not vice-versa.

Pankaj Shukla
  • 2,657
  • 2
  • 11
  • 18
1

The problem here is with your code flow. You've added an event listener, which will fire asynchronously later on. Yet your alert will fire right after the event listener is added, before the change event happens.

If you just want to pull them out of scope, declare value and id above your event listener before using it:

foo = document.getElementById("something"); 

var value, id;
foo.addEventListener('change',  function(e){
    value = this[this.selectedIndex].text
    id    = this[this.selectedIndex].value
}, false);
drquinn
  • 467
  • 4
  • 16
1

I suggest to use an object for the values, because you could collect all values in one object without polluting the global scope to much.

var foo = document.getElementById("something"),
    values = {};

foo.addEventListener('change', function(e) {
    values.value = this[this.selectedIndex].text;
    values.id    = this[this.selectedIndex].value;
}, false);

alert(values.value);

For a more dynamic version, i suggets to use a closure over values.

var foo = document.getElementById("something"),
    values = {};

foo.addEventListener('change', function (object) {
    return function(e) {
        object.value = this[this.selectedIndex].text;
        object.id    = this[this.selectedIndex].value;
    };
}(values), false);

alert(values.value);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392