Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีแสดงดัชนีของตัวเลือกที่เลือกใน Dropdown List ด้วย JavaScript

หากต้องการแสดงดัชนี (index) ของตัวเลือกที่เลือกใน Drop-down List ให้ใช้คุณสมบัติ selectedIndex ใน JavaScript

ตัวอย่าง

ลองรันโค้ดด้านล่างเพื่อแสดงดัชนีของตัวเลือกที่เลือก:

<!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>Select and click the button to get the index of the selected option.</p>
    <script>
      function display() {
        var index = document.getElementById("selectNow").selectedIndex;
        document.write(index);
      }
    </script>
  </body>
</html>

selectedIndex คืนค่าดัชนี (0-based) ของตัวเลือกที่ถูกเลือกอยู่ หากไม่มีการเลือก จะคืน -1 สำหรับ <select multiple> จะคืนดัชนีของตัวเลือกแรกที่ถูกเลือกเท่านั้น ต้องใช้ loop วน options เพื่อหาทุกตัวที่ถูกเลือก