Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Hiển thị chỉ số (index) của tùy chọn được chọn trong dropdown với JavaScript

Thuộc tính selectedIndex của <select> trả về chỉ số (0-based) của option đang được chọn (-1 nếu không có).

Ví dụ

<!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>Chọn và nhấn để lấy index</p>
    <script>
      function display() {
        var index = document.getElementById("selectNow").selectedIndex;
        document.write(index);
      }
    </script>
  </body>
</html>