I have a form that request user data(name) and then when they click the "check" button the form will get replaced by a div and display the name in it. Then when the user clicks the "edit" button the user gets prompt back to the form but with the previous entered data. I want to know how to display the details back in the form.
<html>
<body>
<div id="container">
<h2 id="heading">Query Form</h2>
<br>
<div id="formdiv">
<form id="form" method="POST">
<div>
<label for="name">Name: </label>
<input id="name" name="name" type="text">
</div>
<br>
<button id="checkbutton" onclick=submitform()>Check</button>
<input type="submit" id="formbutton" value="Submit" onclick=validateForm()>
</form>
</div>
<div id="for_replacement">
<div id="display_replacment" style="display: none;">
<form>
<label for="name_submit">Name: </label><span id="name"></span>
<span id="display_name"></span><br><br>
<input type="submit" id="formbutton" value="Edit" onclick="editform()">
</form>
</div>
</div>
<script>
function validateForm() {
var formrefresh = document.getElementById("form");
function handleForm(event) {
event.preventDefault();
}
var namevalidate = document.getElementById("name").value;
if(namevalidate.length == 0) {
alert("Please Enter Name");
formrefresh.addEventListener("submit", handleForm);
return;
}else {
form.action = "mailto:[email protected]"
}
}
function submitform() {
globalThis.name = document.getElementById("name").value;
document.getElementById('container').innerHTML = document.getElementById("display_replacment").innerHTML;
document.getElementById("display_name").innerText = name;
}
function editform() {
alert(globalThis.name);
}
</script>
</body>
</html>
What should happen is when edit is clicked the data entered in the form should be displayed again in the form to edit.
CodePudding user response:
Instead of removing the form why don't you set its display to none:
document.getElementById('heading').style.display = "none";
document.getElementById('form').style.display = "none";
document.getElementById('display_replacment').style.display = "block";
and when you want the get it back reverse
document.getElementById('heading').style.display = "block";
document.getElementById('form').style.display = "block";
document.getElementById('display_replacment').style.display = "none";
and you can get the name from the display_name
:
const name =document.getElementById("display_name").innerText;
document.getElementById("name").value = name;