Get select element value on event using pure JavaScript

那年仲夏 提交于 2019-11-29 17:57:12

问题


I want to get the value of a select element when the select element is clicked! I want to do it without an onchange attribute in the HTML.

I would like to achieve this without jQuery. I don't want to include a jQuery framework into this website when this tiny script is the only thing I need.

var select_element = document.getElementById('product-form-user-enquiry-type');

select_element.onchange = function(e){
    if (!e)
        var e = window.event;
    var svalue = select_element.value;
    alert( svalue );
}
if ( select_element.captureEvents ){
    select_element.captureEvents(Event.CHANGE);
}

The select_element.value; contains an empty string. How should I do this?


回答1:


A solution that will work with all browsers (including IE8) :

var select_element = document.getElementById('product-form-user-enquiry-type');

select_element.onchange = function() {
    var elem = (typeof this.selectedIndex === "undefined" ? window.event.srcElement : this);
    var value = elem.value || elem.options[elem.selectedIndex].value;
    alert(value);
}​



回答2:


​document.getElementById('test').onchange = function() {
    alert(this.options[this.selectedIndex].val​​​ue);
};​

Does the above the work?

Edit:

Edited to reflect your select id's etc.

var select_element = document.getElementById('product-form-user-enquiry-type');

select_element.onchange = function(e){
    if (!e)
        var e = window.event;
    var svalue = this.options[this.selectedIndex].value;
    alert( svalue );
}​

See it working at: http://jsfiddle.net/gRoberts/4WUsG/




回答3:


.onchange = function() { ... } seems to overwrite other handlers, so I use addEventListener("change", function() { ... })



来源:https://stackoverflow.com/questions/11683934/get-select-element-value-on-event-using-pure-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!