Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get select element value on event using pure JavaScript

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?

like image 532
AlexMorley-Finch Avatar asked Jul 27 '12 08:07

AlexMorley-Finch


2 Answers

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);
}​
like image 175
AymKdn Avatar answered Sep 24 '22 08:09

AymKdn


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

like image 26
vladkras Avatar answered Sep 22 '22 08:09

vladkras