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

Thuộc tính required trong HTML

Thuộc tính required trong HTML xác định rằng phần tử HTML phải được điền trước khi submit biểu mẫu trong tài liệu HTML. Nó có thể được áp dụng trên phần tử input, select và textarea.

Cú pháp

Cú pháp như sau:

<tagname required></tagname>

Ví dụ

Dưới đây là ví dụ minh họa thuộc tính required trong HTML:

<!DOCTYPE html>
<html>
<style>
  body {
    color: #000;
    height: 100vh;
    background-color: #8BC6EC;
    background-image: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%);
    text-align: center;
  }
  .btn {
    background: #db133a;
    border: none;
    height: 2rem;
    border-radius: 2px;
    width: 40%;
    display: block;
    color: #fff;
    outline: none;
    cursor: pointer;
    margin: 1rem auto;
  }
</style>
<body>
<h1>Demo thuộc tính required trong HTML</h1>
<p>Chọn môn học yêu thích của bạn:</p>
<form method="post">
  <select required>
    <option value="">Không có</option>
    <option value="Physics">Vật lý</option>
    <option value="Chemistry">Hóa học</option>
    <option value="Biology">Sinh học</option>
  </select>
  <input type="submit" value="Gửi" class="btn">
</form>
</body>
</html>

Kết quả

Thuộc tính required trong HTML

Nhấn vào nút "Gửi" mà không chọn môn học nào từ danh sách thả xuống.

Thuộc tính required trong HTML