Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Alert Selected Option of html drop down [duplicate]

I have searched around and tried various things but I cannot find a way to get javascript to alert my chosen option. All that happens with what I have is in the console debugging section at the bottom of the page it says " 'null' is not an object (evaluating 'x.options') " which suggests to me that my variable x is not getting any value in the first place, here is my code:

html

    <select id=“test-dropdown” onchange=“choice1()”>

    <option value=“1”>One</option>

    <option value=“2”>Two</option>

    <option value=“3”>Three</option>

    </select>

javascript

    function choice1()
    {
    var x = document.getElementById(“test-dropdown”);
    alert(x.options[x.selectedIndex].value);
    }

I would be very thankful if someone could solve the problem or point me in the direction of where this question has been answered before.

like image 806
user3603650 Avatar asked May 05 '14 09:05

user3603650


1 Answers

I believe you want to alert the text of the chosen element, you can do it by doing this in a shorter way too

HTML:

<select id="test-dropdown" onchange="choice1(this)">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

JavaScript:

function choice1(select) {
     alert(select.options[select.selectedIndex].text);
}

Fiddle: http://jsfiddle.net/AwFE3/

like image 175
jsachs Avatar answered Oct 03 '22 07:10

jsachs