Search code examples
jquerytext

Prevent form submission in the onsubmit event


In my project, I have JS and HTML code as following:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>

function myFunction() {
    //document.getElementById('demo').innerHTML = Date();
    alert("done");
    var a = parseInt(document.getElementById('number1').value);
    var b = parseInt(document.getElementById('number2').value);
    var c = a + b;
    $.get('/_add_numbers',{number: c}, function(data,status){
        res = JSON.parse(data);
        alert(status);
        $("#feedback").text("change");
        alert("show");
    });
};

</script>
</head>
<body>
<h1>My First JavaScript V2</h1>
<p id="demo"></p>
<form onsubmit="myFunction()">
    <input type="text" size="5" name="a" id = "number1"> +
    <input type="text" size="5" name="b" id = "number2"> =
    <span id="result">?</span>
    <br>
    <input type="submit" value="calculate server side" >
</form>
<p id="feedback">feedback</p>
</body>
</html> 

And the alert shows that the status was success.

The content of the paragraph turns to "change", but finally change back to original "feeback". So what's the reason ?


Solution

  • The content is not changing back. Actually, the form is being submitted and the page is essentially being refreshed.

    You need to call .preventDefault(); on the submit event to prevent the form submission like this:

    function myFunction(evt) { 
      evt.preventDefault();
    
      // ... other code
    };
    

    Or better yet, ditch the form altogether, change the type="submit" to type="button", then attach an event handler to the button like this:

    <body>
      <h1>My First JavaScript V2</h1>
      <p id="demo"></p>
      <input type="text" size="5" name="a" id="number1"> +
      <input type="text" size="5" name="b" id="number2"> =
      <span id="result">?</span>
      <br>
      <input type="button" class="calculate" value="calculate server side">
      <p id="feedback">feedback</p>
    </body>
    
    $(function() {
      $('.calculate').click(function() {
        alert("done");
        var a = parseInt(document.getElementById('number1').value);
        var b = parseInt(document.getElementById('number2').value);
        var c = a + b;
        $.get('/_add_numbers', {
          number: c
        }, function(data, status) {
          res = JSON.parse(data);
          alert(status);
          $("#feedback").text("change");
          alert("show");
        });
      });
    });