I have two forms, in html, when I submit one of them, the values of the other are reset to default, how can I prevent this behaviour from happening.
Here's the full code:
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>challenge</title>
</head>
<body>
<section >
<div >
<h1>Title</h1>
<form id="firstForm">
<input type="text"><input type="submit" value="Submit">
</form>
<form >
<input type="checkbox" id="form2" ><label for="form2">Checkbox of separated form, that I do not want to reset when first form is submit s=is clicked.</label>
</form>
</div>
</section>
</body>
</html>
CodePudding user response:
to avoid submitting the form, you should use javascript and add preventDefault.
`const submit=document.querySelector("#firstForm")
submit.addEventListener("submit",(e)=>{ e.preventDefault() })`
CodePudding user response:
When you submit a form, the data in it is bundled up into an HTTP request and sent to the server. The server then responds with a new HTML document which the browser displays.
When it generates the new page, the server won't have the data from the other form, so it can't include as it default values in the new page.
There are several approaches you could take:
Combine the forms into a single form, then write server-side code to determine which submit button was used to submit the form so you can act on the right set of data, then use the combined data set of both original forms to generate the default values for the new page.
Don't send any content in the response and use a 204 status instead. The big drawback here is that there's no information passed to the user to tell them that the form was submitted successfully.
Replace the form submission with Ajax. Create an event listener for the form's submit
event, prevent the default behaviour (of submitting the form) and make an HTTP request using the fetch api instead. Then use DOM manipulation to present the result to the user.
Track all the user input with client-side JS and store it somewhere persistent (such as localStorage). Each time the page loads, check for data there to repopulate the fields with.