【问题标题】:Getting an option text/value with JavaScript使用 JavaScript 获取选项文本/值
【发布时间】:2011-06-06 05:33:34
【问题描述】:

回答var option_user_selection = element.options[element.selectedIndex].text

我正在尝试构建一个填写某人订单的表单。

<form name="food_select">
    <select name="maincourse" onchange="firstStep(this)">
        <option>- select -</option>
        <option text="breakfast">breakfast</option>
        <option text="lunch">lunch</option>
        <option text="dinner">dinner</option>
    </select>
</form>

我要做的是发送选择对象,从选项菜单中提取名称和文本/值以及选项标签中的数据。

function firstStep(element) {
    //Grab information from input element object
    /and place them in local variables
    var select_name = element.name;
    var option_value = element.value;
}

我可以获取名称和选项值,但我似乎无法从选择对象中获取 text="" 或 value=""。我只需要用户选择的选项菜单中的文本/值。我知道我可以将它们放在一个数组中,但这无济于事

var option_user_selection = element.options[ whatever they select ].text 

我还需要使用传入的选择引用,因为这就是它在我的其余代码中的设置方式。

稍后,该文本/值将用于提取 XML 文档,该文档将动态填充下一个选择表单。

【问题讨论】:

标签: javascript html forms html-select


【解决方案1】:

你可以使用:

var option_user_selection = element.options[ element.selectedIndex ].text

【讨论】:

  • 有 jQuery 替代品吗?
  • 试试这个$("select[name='maincourse'").find('option:selected').text()
  • @Phil 我之前评论中的 jquery 版本是为了回应 Jacob 的请求。你能详细说明什么是可怕的吗?
  • 天哪,我感觉很糟糕,我以为你是另一个人 纠正 Chandu,但你是 Chandu...O_o 我删除了我的回复...
  • 亲爱的耶稣!我非常需要:)
【解决方案2】:
form.MySelect.options[form.MySelect.selectedIndex].value

【讨论】:

  • 这有真正的教育价值。不需要负分。
【解决方案3】:
var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text

【讨论】:

    【解决方案4】:

    在 jquery 中你可以试试这个$("#select_id&gt;option:selected").text()

    【讨论】:

    • 这并没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方留下评论。 - From Review
    • 为什么不呢?他想要所选值的文本....该代码在选择上返回所选文本...
    • 他好像没有使用jq,也许这就是原因。
    猜你喜欢
    • 2013-02-05
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    相关资源
    最近更新 更多