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

Thuộc tính enctype của Form trong HTML DOM

Thuộc tính enctype của Form trong HTML DOM liên quan đến thuộc tính enctype của phần tử form. Thuộc tính này thiết lập hoặc trả về giá trị enctype của form. Thuộc tính enctype chỉ được sử dụng khi giá trị method là "POST". Enctype dùng để chỉ định cách mã hóa dữ liệu form khi gửi đi.

Cú pháp

Cú pháp để thiết lập thuộc tính enctype:

formObject.enctype = encoding

Các giá trị encoding:

  • "application/x-www-form-urlencoded": Tất cả ký tự được mã hóa trước khi gửi - đây là mã hóa mặc định.
  • "multipart/form-data": Không mã hóa ký tự nào, dùng để upload file lên server.
  • "text/plain": Chuyển đổi khoảng trắng thành dấu "+" và không mã hóa khác. Không nên dùng vì không an toàn.

Ví dụ

Ví dụ minh họa cho thuộc tính enctype của Form:

<!DOCTYPE html> <html> <head> 
<style> 
    form{ border:2px solid blue; margin:2px; padding:4px; } 
</style> 
<script> 
    function changeEnc() { 
        document.getElementById("FORM1").enctype = "application/x-www-form-urlencoded"; 
        document.getElementById("Sample").innerHTML = "Giá trị thuộc tính enctype bây giờ là 'application/x-www-form-urlencoded'"; 
    } 
</script> </head> <body> 
<h1>Ví dụ thuộc tính enctype của Form</h1> 
<form id="FORM1" method="post" enctype="multipart/form-data"> 
    <label>Tên người dùng <input type="text" name="usrN"></label> <br><br> 
    <label>Mật khẩu <input type="password" name="pass"></label> 
</form> 
<br> 
<button onclick="changeEnc()">THAY ĐỔI</button> 
<p id="Sample"></p> 
</body> </html>

Kết quả

Khi nhấn nút "THAY ĐỔI", enctype chuyển từ "multipart/form-data" sang "application/x-www-form-urlencoded".

Giải thích ví dụ

Tạo form với id="FORM1", method="post" và enctype="multipart/form-data". Encoding này hữu ích cho upload file. Form chứa trường text và password.

Tạo nút "THAY ĐỔI" thực thi hàm changeEnc():

<button onclick="changeEnc()">THAY ĐỔI</button>

Hàm changeEnc() lấy form bằng getElementById() và thiết lập enctype thành "application/x-www-form-urlencoded" (mặc định). Hiển thị thông báo thay đổi:

function changeEnc() { 
    document.getElementById("FORM1").enctype = "application/x-www-form-urlencoded"; 
    document.getElementById("Sample").innerHTML = "Giá trị thuộc tính enctype bây giờ là 'application/x-www-form-urlencoded'"; 
}