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

Tại sao formaction không hoạt động ngoài thẻ <form> và cách khắc phục

Thuộc tính formaction trên nút submit chỉ hoạt động khi nút nằm bên trong thẻ <form>. Nếu đặt nút bên ngoài, nó không biết submit form nào.

Giải pháp: Dùng thuộc tính form trên nút submit, trỏ đến id của form. Như vậy nút có thể đặt bất kỳ đâu trong trang.

Ví dụ: Nút submit bên ngoài form

<!DOCTYPE html>
<html>
  <head>
    <title>HTML formaction attribute</title>
  </head>
  <body>
    <form method="post" id="newForm">
      <input type="text" name="name"/>
    </form>
    <button type="submit" formaction="btn1.php" form="newForm">Nút 1</button>
    <button type="submit" formaction="btn2.php" form="newForm">Nút 2</button>
    <button type="submit" formaction="btn3.php" form="newForm">Nút 3</button>
  </body>
</html>

Cơ chế: form="newForm" liên kết nút với form có id="newForm". formaction chỉ định URL xử lý cho từng nút.