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

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

Thuộc tính name của <select> (danh sách thả xuống) trả về hoặc thiết lập tên trường form. Dùng làm key khi submit form (VD: $_POST['mon_hoc']).

Cú pháp

Lấy giá trị:

selectElement.name

Thiết lập giá trị:

selectElement.name = "ten_moi"

Ví dụ: Hiển thị name của select

<!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: 35%; border: 2px solid white; font-weight: bold;
            padding: 8px; background: rgba(255,255,255,0.1); color: white;
            margin: 15px auto; display: block; outline: none;
        }
        .btn {
            background: #0197F6; border: none; color: white;
            padding: 10px 20px; border-radius: 4px; width: 35%;
            margin: 20px auto; display: block; cursor: pointer;
        }
        .show { font-size: 1.5rem; font-weight: bold; margin-top: 15px; }
    </style>
</head>
<body>
    <h1>Ví dụ Select name Property</h1>
    <p>Chọn môn học yêu thích:</p>
    <select class="drop-down" name="Danh_Sach_Mon_Hoc">
        <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="showName()" class="btn">Hiện Name</button>
    <div id="result" class="show"></div>
    <script>
        function showName() {
            var select = document.querySelector(".drop-down");
            document.getElementById("result").textContent = "Chào! Tôi là " + select.name;
        }
    </script>
</body>
</html>

Kết quả

Select có name="Danh_Sach_Mon_Hoc":

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

Nhấn "Hiện Name":

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

ℹ️ Lưu ý: Thuộc tính name trên <select> là **bắt buộc** để giá trị được gửi lên server. Nếu multiple, server nhận được mảng giá trị.