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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With