简体   繁体   English

javascript表单提交不起作用

[英]javascript form submit not working

As according to the advice at Prevent form redirect OR refresh on submit? 根据防止表单重定向或刷新提交时的建议? , I have my form which is ,我的表格是

<form id="editingForm">
  Line height (between 10 and 60): 
  <input type="number" id="LineHeightEntry" name="LineHeightEntry" min="10" max="60" value="30">
  <input type="submit" id="submitLineChange" value="Submit">
</form>

In a file called test.html. 在一个名为test.html的文件中。 The javascript is javascript是

$('#editingForm').submit(function(){
  alert("abc");
  return false;
});

The intent is to have the function be called, and then javascript can do something to the page, but the page is not reloaded or redirected elsewhere. 目的是要调用该函数,然后javascript可以对页面执行操作,但是该页面不会重新加载或重定向到其他地方。 However, instead what I get is say I set LineHeightEntry to 40 and hit submit. 但是,我得到的却是说我将LineHeightEntry设置为40并点击Submit。 Then it redirects to test.html?LineHeightEntry=40. 然后将其重定向到test.html?LineHeightEntry = 40。 Why does it do that? 为什么这样做呢?

edit - The file is at http://probuling.net/sandbox/test.html 编辑-该文件位于http://probuling.net/sandbox/test.html

Here is a working example: 这是一个工作示例:

<html>
<head>
<script src="jquery-1.9.1.min.js"></script>
</head>
    <form id="editingForm" action="toto">
      Line height (between 10 and 60): 
      <input type="number" id="LineHeightEntry" name="LineHeightEntry" min="10" max="60" value="30">
  <input type="submit" id="submitLineChange" value="Submit">
</form>
<script>
$('#editingForm').submit(function(event)
{
  alert("abc");
event.preventDefault(); // if you want to disable the action
  return false;

});
</script>
</html>

Add action attribute to the form or you are just refreshing the page on submit. 将操作属性添加到表单,或者您只是在提交时刷新页面。

<form id="editingForm" action="/another/url">

I would recommend learning how to use normal form submit before even try using Javascript. 我建议您在尝试使用Javascript之前,先学习如何使用普通表单提交。 Any input with name attribute will be appended to the URL since you have no action and default method is set to GET. 由于您没有任何操作,并且默认方法设置为GET,因此任何具有name属性的输入都将附加到URL。

remove line return false; 删除行返回false;

This prevent default event. 这样可以防止发生默认事件。 Read more detail: http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/ 阅读更多详细信息: http : //fuelyourcoding.com/jquery-events-stop-misusing-return-false/

try doing it without jQuery. 尝试在没有jQuery的情况下进行操作。 Also, try using the event.preventDefault 另外,尝试使用event.preventDefault

document.querySelector('#editingForm').onsubmit = function(event) {
  alert('abc');
  event.preventDefault();
  return false;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM