html 下拉列表的 JavaScript Alert Selected 选项 [英] JavaScript Alert Selected Option of html drop down

查看:36
本文介绍了html 下拉列表的 JavaScript Alert Selected 选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我四处搜索并尝试了各种方法,但我找不到让 javascript 提醒我选择的选项的方法.所有发生的事情都在页面底部的控制台调试部分,它说'null'不是一个对象(评估'x.options')"这向我表明我的变量x没有得到任何首先是值,这是我的代码:

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:

JavaScript:

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

小提琴:http://jsfiddle.net/AwFE3/

这篇关于html 下拉列表的 JavaScript Alert Selected 选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆