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

Thuộc tính multiple của Select trong HTML DOM

Thuộc tính multiple của <select> cho phép trả về hoặc thiết lập việc **cho phép chọn nhiều tùy chọn** cùng lúc (giữ Ctrl/Command hoặc Shift). Mặc định là false (chọn đơn).

Cú pháp

Lấy giá trị:

selectElement.multiple

Thiết lập giá trị:

selectElement.multiple = true | false

Ví dụ: Bật chế độ chọn nhiều

<!DOCTYPE html>
<html>
<head>
    <style>
        html, body { height: 100%; margin: 0; font-family: sans-serif; }
        body {
            text-align: center; color: white;
            background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;
        }
        .drop-down {
            width: 50%; border: 2px solid white; font-weight: bold;
            padding: 8px; background: rgba(255,255,255,0.15);
            margin: 15px auto; display: block;
        }
        .btn {
            background: #0197F6; border: none; color: white;
            padding: 10px 20px; border-radius: 4px; width: 45%;
            margin: 20px auto; display: block; cursor: pointer;
        }
        .show { font-size: 1.1rem; font-weight: bold; margin-top: 15px; }
    </style>
</head>
<body>
    <h1>Demo Select multiple Property</h1>
    <p>Chọn môn học yêu thích (có thể chọn nhiều):</p>
    <select class="drop-down" id="subjectSelect">
        <option>Vật lý</option>
        <option>Toán học</option>
        <option>Hóa học</option>
        <option>Tiếng Anh</option>
    </select>
    <button onclick="enableMultiple()" class="btn">Bật chọn nhiều (Multiple)&lt;/button>
    <div id="result" class="show"></div>
    <script>
        function enableMultiple() {
            var select = document.getElementById("subjectSelect");
            var msg = document.getElementById("result");
            select.multiple = true;
            select.size = 4; // Hiển thị 4 option cùng lúc khi multiple
            msg.textContent = "Đã bật multiple! Giữ Ctrl/Shift để chọn nhiều.";
        }
    </script>
</body>
</html>

Kết quả

Select đơn (mặc định):

Thuộc tính multiple của Select trong HTML DOM

Nhấn "Bật chọn nhiều" - select hiển thị dạng list, cho phép chọn nhiều:

Thuộc tính multiple của Select trong HTML DOM

✅ Thực hành:
  • Khi multiple=true, nên set size > 1 để hiển thị dạng danh sách.
  • Lấy giá trị multiple: Array.from(select.selectedOptions).map(o => o.value).
  • Submit form: name cần có [] (PHP) hoặc server tự xử lý mảng (Node.js, Python...).
  • UI/UX: Cân nhắc dùng checkbox group thay vì select multiple cho dễ dùng hơn trên mobile.