防止在onsubmit事件中提交表单 [英] Prevent form submission in the onsubmit event

查看:59
本文介绍了防止在onsubmit事件中提交表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我具有以下JS和HTML代码:

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> 

警报显示状态为成功.

该段的内容变为更改",但最终更改为原始的反馈".那是什么原因呢?

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

推荐答案

内容没有改回.实际上,正在提交表单,并且实质上是在刷新页面.

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

您需要在Submit事件上调用.preventDefault();,以防止这样的表单提交:

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

function myFunction(evt) { 
  evt.preventDefault();

  // ... other code
};

或者更好的方法是,完全放弃表单,将type="submit"更改为type="button",然后将事件处理程序附加到按钮上,如下所示:

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");
    });
  });
});

这篇关于防止在onsubmit事件中提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆