How to stop form auto-reset in JS and HTML?

谁都会走 提交于 2021-02-11 13:54:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!