简体   繁体   中英

Native JavaScript select onchange this.value undefined

I have a select tag that is generated by a php file that I would rather not have to change if it can be avoided. I also do not have the ability to use jQuery to solve my problem. So here is how I am trying to set an onchange event:

var d = document.getElementById('lang_choice');
d.onchange = function(){
    window.alert(this.value);
}

The pop up box just says undefined. I have checked the html and it has the value attributes set in the option tags. So I am guessing I misunderstand something about this system and some explanation would be great.

var d = document.getElementById('lang_choice');
d.onchange = function(){
    window.alert(this.options[this.selectedIndex].value);
}

It works in older browser.

Although your method should work. There must be error elsewhere in your code. Check console.

Please make sure that you bind onchange event once DOM object available and make sure option tag value attribute.

<select id="lang_choice">
  <option value="en">English</option>
  <option value="es">Spanish</option>
</select>

This is helped for me.

For select:

$('select_tags').on('change', function() {
    alert( $(this).find(":selected").val() );
});

For radio/checkbox:

$('radio_tags').on('change', function() {
    alert( $(this).find(":checked").val() );
});

IE has a bug(Not sure about versions), onchange will be fired before even value is set, so use like below

var d = document.getElementById('lang_choice');
d.onchange = function(){
   var th = this;
   setTimeout(function(){ window.alert( th.value ); }, 10);
}

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