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

Thuộc tính form của Textarea trong HTML DOM

Thuộc tính form của đối tượng HTMLTextAreaElement trả về tham chiếu đến phần tử <form> **bao quanh** textarea đó (nếu có). Nếu textarea không nằm trong form nào, trả về null. Đây là thuộc tính **chỉ đọc (read-only)**.

Cú pháp

var formRef = textareaElement.form;

Ví dụ: Xác định form chứa textarea

<!DOCTYPE html>
<html>
<style>
  body { text-align: center; background: #363946; color: #fff; }
  form { margin: 2.5rem auto; }
  button { background: #db133a; border: none; cursor: pointer; padding: 8px 16px; color: #fff; border-radius: 5px; font-size: 1.05rem; }
  .show { font-weight: bold; font-size: 1.4rem; margin-top: 1rem; }

<body>
  <h1>Demo: textarea.form</h1>
  <form id="formDangKy">
    <fieldset>
      <legend>Form Đăng ký</legend>
      <textarea rows="5" cols="30">Nội dung ghi chú...</textarea>
    </fieldset>
  </form>
  <button onclick="identifyForm()">Xác định Form chứa textarea</button>
  <p class="show" id="result"></p>
  <script>
    function identifyForm() {
      var ta = document.querySelector("textarea");
      var formId = ta.form ? ta.form.id : "Không có form";
      document.getElementById("result").textContent = "Textarea thuộc form: " + formId;
    }
  </script>
</body>
</html>

Kết quả:

Nhấn nút → Hiển thị: "Textarea thuộc form: formDangKy"

Ứng dụng thực tế

  • Từ textarea, truy xuất form cha để: ta.form.submit(), ta.form.reset(), ta.form.elements (lấy tất cả controls).
  • Kiểm tra textarea có trong form không trước khi submit AJAX.
  • Textarea có thể nằm **ngoài form** nhưng vẫn liên kết qua thuộc tính form="formId" (HTML5):
<form id="myForm"></form>
<textarea form="myForm"></textarea> <!-- Nằm ngoài nhưng thuộc form -->

Trong trường hợp này, textarea.form vẫn trả về form có id="myForm".

Lưu ý

  • Thuộc tính form chỉ đọc — không thể gán ta.form = otherForm.
  • Nếu textarea nằm trong form lồng nhau (invalid HTML), hành vi không xác định.