Advaith Advaith - 2 months ago 6
HTML Question

Webpage reloading in every form submit

I have a problem of page reloading.

HTML

<form onsubmit="return commentForm()">
<input type="text" id="text">
<input type="checkbox" id="check" name="check">
<input type="submit" value="Comment" class="txt2">
</form>
<p id="demo"></p>


Javascript

function commentForm() {
var x = document.getElementById('check').checked;
var y = document.getElementById('text').value;
if (y == null || y == "") {
alert('please enter some value');
return false;
}
if (x == false) {
alert('Please check the checkbox')
return false;
}
else {
document.getElementById('demo').innerHTML += document.getELementById('text').value + "<br>";
return true;
}
}


My problem is that when i submit the page it is reloading instead of copying the text.

Please help me with that.

Answer

function commentForm() {
     var x = document.getElementById('check').checked;
     var y = document.getElementById('text').value;
     if (y == null || y == "") {
          alert('please enter some value');
          return false; 
     }
     if (x == false) {
          alert('Please check the checkbox')
          return false;
     }
     else {
          document.getElementById('demo').innerHTML += document.getElementById('text').value + "<br>";
          return false;
     }
}
<form onsubmit="return commentForm()">
     <input type="text" id="text">
     <input type="checkbox" id="check" name="check">
     <input type="submit" value="Comment" class="txt2">
</form>
<p id="demo"></p>

If you want the page not to be redirected you can use the return false in the else statement.