Computer >> Máy Tính >  >> Lập trình >> Javascript

Làm cách nào để hiển thị tất cả các tùy chọn từ danh sách thả xuống bằng JavaScript?


Để hiển thị tất cả các tùy chọn từ danh sách thả xuống, hãy sử dụng tùy chọn bất động sản. Thuộc tính cho phép bạn nhận tất cả các tùy chọn với chiều dài tài sản.

Ví dụ

Bạn có thể thử chạy đoạn mã sau để nhận tất cả các tùy chọn từ danh sách thả xuống.

<!DOCTYPE html>
<html>
   <body>
      <form id="myForm">
         <select id="selectNow">
            <option>One</option>
            <option>Two</option>
            <option>Three</option>
         </select>
         <input type="button" onclick="display()" value="Click">
      </form>
      <p>Click the button to get all the options</p>
      <script>
         function display() {
            var a, i, options;
            a = document.getElementById("selectNow");
            options = "";
            for (i = 0; i < a.length; i++) {
               options = options + "<br> " + a.options[i].text;
            }
            document.write("DropDown Options: "+options);
         }
      </script>
   </body>
</html>