5

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.

user3603650
  • 57
  • 1
  • 1
  • 4
  • 1
    Duplicate but -- not all browsers fire a change event when you think they would.... I tend to bind to both `change` and `click` to make sure both are covered. – Jeremy J Starcher May 05 '14 at 09:38
  • 1
    There seems to be some problem in encoding your code. your code is working fine for me http://jsfiddle.net/praveen_jegan/7K4AK/ Better type the whole code to avoid UTF encoding. – Praveen May 05 '14 at 09:50
  • 1
    thanks it seems as its on my mac speech marks don't work properly unless copied. took your script and it worked fine. – user3603650 May 05 '14 at 10:06

2 Answers2

12

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/

jsachs
  • 519
  • 2
  • 5
-1

Try below code : JSFIDDLE

$( "select" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).text() + " ";
});
alert(str)
})
Lachu
  • 47
  • 1
  • 2
  • 9