Trong hàm xử lý onsubmit, truy cập document.formName.inputName.value để sửa giá trị trước khi gửi.
Ví dụ
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Thay giá trị khi submit</title>
</head>
<body>
<form name="studentForm" onsubmit="return submitForm()">
<input type="hidden" name="txtInput" value="10000" />
<input type="submit" value="Gửi Form" />
</form>
<script>
function submitForm() {
document.studentForm.txtInput.value = 'STUDENT-100';
return true; // Cho phép submit
}
</script>
</body>
</html>
Cách chạy
Lưu index.html, mở Live Server, nhấn "Gửi Form", xem URL query string.
Kết quả
URL sẽ chứa ?txtInput=STUDENT-100 thay vì ?txtInput=10000.
Lưu ý: Trả về false trong onsubmit để hủy submit nếu validation fail.