问题
I have a form that is defined as follows:
<form id="form" onsubmit="validate()">
I process information and then modify the body of the HTML as follows:
var toRemove = document.getElementById("formContainer");
toRemove.parentNode.removeChild(toRemove);
document.getElementById("main").childNodes[1].innerHTML = text1;
document.getElementById("main").childNodes[3].innerHTML = text2;
This displays corectly for a milisecond maybe, but then the page resets to the blank form. I can fix this by adding an alert afterwards, but as soon as I dismiss the alert the page resets. Is there a way to stop it from resetting?
Here is the full code:
HTML - http://puu.sh/p7HIl/e1abcc7920.html JavaScript - http://puu.sh/p7HJ3/54850f8588.js
Also here is a live version - http://139.62.210.151/~n00876544/assign2/index.html?firstName=Cameron&lastName=Bixby&age=21-30&email=Other&baduk=yes
回答1:
I presume the js snippets are written inside validate
function
If it is so you can use event.preventDefault()
function which will block the default behavior .
function validate(event){
event.preventDefault();
//Rest of the code
}
Note: This will stop from submitting the form. But you can use ajax
to send form data
回答2:
The classic method to prevent form submission was to return false from the event handler, as in
<form id="form" onsubmit="validate(); return false;">
or if the validate function returns false to prevent submission, as
<form id="form" onsubmit="return validate();">
You can also prevent the default action by calling preventDefault
on the event object. The event object is passed as the first parameter to event handler functions, or set as a window property in older versions of IE. In either case you
can prevent the default immediately,
<form id="form" onsubmit="event.preventDefault(); validate();">
or pass it to the validation routine where perhaps preventDefault
can be called conditionally.
<form id="form" onsubmit="validate(event)">
Note that HTMLelement.addEventListener functionality provides an alternative to writing javascript event handlers as HTML attribute values and has the advantage of minimizing conflicts between multiple scripts trying to set the same " onEvent" HTML element attribute on the same HTML element.
来源:https://stackoverflow.com/questions/37495268/how-to-stop-form-auto-reset-in-js-and-html