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


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

示例

你可以嘗試執行以下程式碼來學習如何更改下拉列表的選中值。這裡,我們有一個預設的第一個選擇選項,但是警告顯示的是第二個選項,該選項已使用 val 方法更改。

線上演示

<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>

更新於:17-12-2019

8K+ 瀏覽量

開啟你的 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.