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

Cách chọn trước (preselect) mục trong <select> bằng JavaScript?

Để chọn trước một mục trong danh sách <select> bằng JavaScript, sử dụng thuộc tính selectedIndex. Gán chỉ số (index) của mục bạn muốn chọn (bắt đầu từ 0).

Ví dụ

<!DOCTYPE html>
<html>
<head>
    <title>Preselect List Item</title>
</head>
<body>
    <p>Chọn một mục:</p>
    <form>
        <select id="dropdown" name="dropdown" class="form-control">
            <option value="Java">Java</option>
            <option value="Discrete Mathematics">Toán rời rạc</option>
            <option value="Digital Electronics">Điện tử số</option>
        </select>
    </form>
    <script>
        // Chọn mục index 2 (mục thứ 3: "Digital Electronics")
        document.getElementById("dropdown").selectedIndex = "2";
    </script>
</body>
</html>

Giải thích:

  • selectedIndex = 0 → mục đầu tiên.
  • selectedIndex = -1 → không chọn gì (nếu không có required).
  • Cách này ghi đè lên selected trong HTML.

Cách hiện đại hơn (theo giá trị value):

const select = document.getElementById("dropdown");
select.value = "Digital Electronics"; // Chọn theo value

Cách dùng .value trực quan hơn, không cần nhớ index.