【问题标题】:How to get the value of a selected option of a pull down menu using jquery?如何使用 jquery 获取下拉菜单的选定选项的值?
【发布时间】:2012-08-22 19:20:38
【问题描述】:
  <select id="testSelection">
           <option> test1 </option> 
           <option> test2 </option> 
           <option> test3 </option> 
           <option> test4 </option> <--- selected this one from the pull down menu 
           <option> test5 </option> 
           <option> test6 </option> 
  </select>

             $("#testSelection").change(function()
             {
                    alert($(this).text());
             });

对我来说很奇怪,警报消息显示了所有选择,但我希望它只显示在 test4 文本上。

【问题讨论】:

标签: jquery


【解决方案1】:
<select id="testSelection">
    <option value="1">test1</option>
    <option value="2">test2</option>
    .....
</select> 

这真的取决于你想要什么:

$("#testSelection").on('change', function() {
    // if you just want the text/html inside the select (ie: test1, test2, etc)
    alert($(this).find('option:selected').text()); 

    // or you want the actual value of the option <option value="THISHERE">
    alert($(this).val()); 
});​

jsFiddle DEMO

【讨论】:

  • 这是假的,两种方法都返回被选项目的value=""。我相信这就是你想要展示的:jsfiddle.net/XCSgG/4。第一个 val() 应该是 text() 以返回所选值的文本。第二个 val() 将返回选择菜单的值。
  • 感谢您的关注!将它们像假人一样向后放置(也意外地为 :selected 键入了 .val())
【解决方案2】:

您需要使用val() 函数,而不是text() 函数。

$("#testSelection").change(function()
{
    alert($(this).val());
});​

【讨论】:

    【解决方案3】:

    $(this).text() 返回元素内的所有文本,在本例中为 select 元素。这就是你得到"test1 test2 ..."的原因。

    假设您想要所选选项的文本:

    $(this).find(':selected').text()
    

    如果您想要所选选项的 value 属性,那么 @mcpDESIGNS 的答案将起作用。但是,请注意,您需要将 value 属性添加到您的 option 元素中,如下所示:

    <option value="test4">test4</option>
    

    【讨论】:

      猜你喜欢
      • 2011-02-16
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-09
      • 2015-05-20
      相关资源
      最近更新 更多