如何使用 jQuery 從下拉列表(選擇框)中獲取所選文字?


使用 jQuery,可以使用 :selected 輕鬆地從下拉列表中獲取所選文字。這是使用選擇器 id 完成的。你可以嘗試執行以下程式碼來了解如何使用 jQuery 從下拉列表中獲取所選文字 −

示例

線上演示

<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() {
            $("#submit").click(function(){      
               $("#myselection option:selected").text();
               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>
        </select>
        <button id="submit">Result</button>
      </div>
   </body>
</html>    

更新於:12-Jun-2020

893 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.