Clear Form After Submission In Javascript
I see this has been asked multiple times but after trying all different combinations, I'm still unable to clear form upon submission. I'm just a beginner in HTML and JS so my code
Solution 1:
Give your form an id and use the following script
<script>functionmyFunction() {
document.getElementById("myForm").reset();
}
</script>
Demo
<formid="myForm">
First name: <inputtype="text"name="fname"><br>
Last name: <inputtype="text"name="lname"><br><br><inputtype="button"onclick="myFunction()"value="Reset form"></form><script>functionmyFunction() {
document.getElementById("myForm").reset();
}
</script>
Solution 2:
You did not set the ID to your form but were using it in the Javascript code :)
<html><body><style>body{ background-color:powderblue;}
h1{text-align:center}
h1{color:purple;}
</style><h1>Fill up the details</h1><formname="myform"id="myform">
Name: <inputtype="text"value=""name="name"\><br><br>
Class: <inputtype="text"value="" ></td><br><br>
Register No.: <inputtype="number"value="" ><br><br>
Username: <inputtype="text"value=""name="username"\><br><br>
Password: <inputtype="password"value=""name="password1"\><br><br>
Re-enter Password: <inputtype="password"value=""name="password2"\><br><br>
Mobile No.: <inputtype="number"value="" \><br><br>
Email: <inputtype="text"value="" \><br><br></form><scripttype="text/javascript">functionshow_alert()
{
var name=document.myform.name.value;
var password1=document.myform.password1.value;
var password2=document.myform.password2.value;
if (name==null || name=="")
{
alert("Name can't be blank");
}
elseif(password1!=password2)
{
alert("password must be same!");
returnfalse;
}
elseif(password1.length<6)
{
alert("Password must be at least 6 characters long.");
returnfalse;
}
else
{
alert("Your account has been created!!!!!");
reset();
returnfalse;
}
}
functionreset(){
console.log('reset called');
var form=document.getElementById("myform");
form.reset();
alert("Form has been reset.");
}
</script><inputtype="button"value="Submit"onclick="show_alert()" /><inputtype="reset"value="Reset"onclick="reset()" /></body></html>
PS. You can also use <input type='reset'>
to reset the form. More info here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
Post a Comment for "Clear Form After Submission In Javascript"