我尝试使用JavaScript提交表单,我的测试已经完成。我一直收到一条JavaScript错误Uncaught TypeError: formElement.submit is not a function
。
这是我添加事件监听器的代码:
window.onload = function ()
{
//Event Listeners
var messageForm = document.getElementById("messageForm");
messageForm.addEventListener("submit",handleSubmit);
}
这是我的功能,执行formElement.submit();
时发生错误。这是我的全部功能:
function handleSubmit(ev) {
//Prevent default form submittion
ev.preventDefault();
//Validate the form
var isValid = validation(this),
error,
formElement = this,
submitButton = this.querySelector("input[type=submit]");
//Check if validation passes
if (isValid == true) {
//Check if a file has been selected
var file = this.querySelector("input[type=file]");
if (file != "") {
//Generate a new form
var f = document.createElement("form");
f.setAttribute("method", "POST");
f.setAttribute("enctype", "multipart/form-data");
//Create FormData Object
var formData = new FormData(f);
//Append file
formData.append("image", file.files[0], "image.jpg");
formData.append("source", "message");
//Uploaded
var xhr = new XMLHttpRequest();
xhr.open("POST", "php/uploadImage.php", true);
xhr.onload = function(e) {
if (xhr.status == 200) {
//Parse XML response
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(xhr.responseXML,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(xhr.responseXML);
}
var imageuploaded = xmlDoc.getElementsByTagName("uploaded").nodeValue;
var imageerror = xmlDoc.getElementsByTagName("imageerror").nodeValue;
if (imageuploaded != "") {
formData.append("location",imageuploaded);
formElement.submit();
} else {
message = "Error uploading image: " + imageerror;
}
} else {
message = "Unable to submit form! Please contact admin: " + xhr.description;
}
};
//Progress
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var currentPercentage = Math.round(e.loaded / e.total * 100)-1;
submitButton.innerHTML = "UPLOAD IMAGE " + currentPercentage + "%";
submitButton.style.backgroundSize = (currentPercentage+1) + "% 100%";
if (currentPercentage==99) {
submitButton.innerHTML = "Processing image";
}
}
};
//Send data
xhr.send(formData);
} else {
//Submit form with no file
this.submit();
}
} else {
//Validation failed
ev.preventDefault();
message = "Error: Please ensure you have completed required information!";
}
}