Thuộc tính selectedIndex của HTML DOM Select trả về và cho phép thay đổi chỉ số của tùy chọn được chọn trong danh sách thả xuống trong tài liệu HTML.
Cú pháp
Cú pháp như sau:
Lấy selectedIndex:
object.selectedIndex
Thiết lập selectedIndex:
object.selectedIndex = “số"
Ví dụ
Dưới đây là ví dụ về thuộc tính selectedIndex của HTML DOM Select:
<!DOCTYPE html> <html> <head> <style> html{ height:100%; } body{ text-align:center; color:#fff; background: radial-gradient( circle farthest-corner at 23.1% 64.6%, rgba(129,125,254,1) 0%, rgba(111,167,254,1) 90% ) no-repeat; height:100%; } p{ font-weight:700; font-size:1.1rem; } .drop-down{ display:block; width:35%; border:2px solid #fff; font-weight:bold; padding:2px; margin:1rem auto; outline:none; } .btn{ background:orange; border:none; height:2rem; border-radius:2px; width:35%; margin:2rem auto; display:block; color:#fff; font-weight:bold; outline:none; cursor:pointer; } .show{ font-size:1.5rem; font-weight:bold; } </style> </head> <body> <h1>Demo thuộc tính selectedIndex của DOM Select</h1> <p>Chào bạn, hãy chọn môn học yêu thích:</p> <select class='drop-down' name="Drop Down List"> <option>Vật lý</option> <option>Toán học</option> <option>Hóa học</option> <option>Tiếng Anh</option> <option>Kinh tế</option> <option>Tiếng Hindi</option> <option>Sinh học</option> </select> <button type="button" onclick="set()" class="btn">Đặt selectedIndex</button> <div class="show"></div> <script> function set() { var dropDown = document.querySelector(".drop-down"); document.querySelector(".show").innerHTML="Đặt selectedIndex = '3'"; dropDown.selectedIndex="3"; } </script> </body> </html>
Kết quả
Đoạn mã trên sẽ cho kết quả như sau:

Nhấn vào nút 「Đặt selectedIndex」 để thiết lập selectedIndex='3' trên danh sách thả xuống.
