如何使用 jQuery 獲取下拉列表的選中值?


使用 jQuery,可以輕鬆從下拉列表中獲取選中文字。這是使用 select id 完成的。若要更改下拉列表的選中值,請使用 val() 方法。

示例

你可以嘗試執行以下程式碼來學習如何更改下拉列表的選中值。這裡,我們有一個預設選中選項first,但警報顯示了second 選項,它已使用val method() 更改。

實際演示

<html>

   <head>
      <title>jQuery Selector</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   
      <script>
         $(document).ready(function() {
           $("#button1").click(function(){
              $("#myselection").val('2');
                 alert( $("#myselection option:selected").text() );
            });
         });
   </script>
   </head>
   
   <body>

      <div>
        <p>The selected value:</p>
        <select id="myselection">
          <option value="1">First</option>
          <option value="2">Second</option>
          <option value="3">Third</option>
        </select>
      </div>
     <button id="button1">Click</button>

   </body>
</html>

更新於: 2019年12月17日

8 千+ 瀏覽

開啟你的職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.