简体   繁体   English

为什么要提交我的HTML表单?

[英]Why is my HTML form being submitted?

I have this form with 1 field. 我有1个字段的此表单。 I want that when the user clicks or hits enter it should call a JavaScript function that will do validation and either display an error message or submit the form. 我希望当用户clicks或点击enter它应该调用一个JavaScript函数,该函数将进行验证并显示错误消息或提交表单。

However, when hitting enter it submits the form regardless. 但是,在按enter它将提交表格。 (So far in my JavaScript validation function I only have alert ("Hello World") ) (到目前为止,在我的JavaScript验证功能中,我只有alert ("Hello World")

<form  action="add-another-number-to-dnc.cshtml" method="post" id="addDNCform">
    <h4>Enter 10-digit phone number without dashes, dots or parenthesis</h4> 
    <input type="text" name="pn" required placeholder="phone number" 
        title="Phone Number to Add to Do-Not-Call List" 
        onkeypress="if (event.keyCode == 13) document.getElementById('btnVldt').click()"/> <!-- all this is to treat [Enter] as a click -->
    <input id="btnVldt" type="button" value="Add Number to Do Not Call list" onclick="submitDNC()"/>
</form>

I added all the page code in jsFiddle where you can test and verify that: 我在jsFiddle中添加了所有页面代码,您可以在其中测试和验证以下内容:

  • when clicking on the button, it correctly doesn't submit the form 单击按钮时,它没有正确提交表单
  • when hitting enter it gives you an Error 404 which must mean, it's trying to load the page. 按下enter时,您会看到错误404,该错误必须表示正在尝试加载页面。

Added this: 添加了以下内容:

Actually, if I use submit instead of button , it doesn't work also when clicking. 实际上,如果我使用submit而不是button ,则单击时也无法使用。 However, in jsFiddle it seems to work. 但是,在jsFiddle它似乎可以工作。

Expanding on Praveen's answer here, I'm going to write the JavaScript "unobtrusively" to further separate function, presentation, and content: 在此扩展Praveen的答案时,我将“毫不费力地”编写JavaScript以进一步分离功能,表示形式和内容:

HTML 的HTML

<form action="add-another-number-to-dnc.cshtml" method="post" id="addDNCform">
    <h4>Enter 10-digit phone number without dashes, dots or parenthesis</h4> 
    <input type="text" name="pn" required placeholder="phone number"  title="Phone Number to Add to Do-Not-Call List" />
    <button type='submit'>Add Number to Do Not Call list"</button>
</form>

(X)HTML5 (X)HTML5

Assuming that you want a 10-digit number in the box (numeric characters only), we can also use the pattern attribute on the <input> element in HTML5 as a form of validation for newer browsers (Firefox, Chrome, IE10, Opera): 假设您要在框中输入10位数字(仅数字字符),我们还可以将HTML5中<input>元素上的pattern属性用作对较新浏览器(Firefox,Chrome,IE10,Opera)的一种验证形式:

<form action="add-another-number-to-dnc.cshtml" method="post" id="addDNCform">
    <h4>Enter 10-digit phone number without dashes, dots or parenthesis</h4> 
    <input type="text" name="pn" required placeholder="phone number" title="Phone Number to Add to Do-Not-Call List" pattern="[0-9]{10}" />
    <button type='submit'>Add Number to Do Not Call list"</button>
</form>

JavaScript (place inside <script> tags somewhere on the page) JavaScript(放在<script>标记内的页面上)

function submitDNC(event) {
    var valid = false;

    alert('Hello world');
    // your validation logic goes here, sets valid to TRUE if it's valid

    if(!valid) {
        event.preventDefault();
    }
}

document.getElementById('addDNCform').addEventListener( 'submit', submitDNC, false );

No need to do any synthetic button clicking if all you're trying to do is validate upon form submission. 如果您要做的只是在提交表单时进行验证,则无需进行任何合成按钮单击。 Pretty soon with HTML5 we might not even need JavaScript for this, depending on what your validation logic is. 很快,借助HTML5,我们甚至可能不需要JavaScript,具体取决于您的验证逻辑是什么。

In your submitDNC() function, give a return false; 在您的submitDNC()函数中, return false; submitDNC()return false; .

function submitDNC()
{
    alert("Hello World!");
    return false;
}

Another thing is, change your input type from button to submit . 另一件事是,将input类型从button更改为submit Use: 采用:

<input id="btnVldt" type="submit"
       value="Add Number to Do Not Call list" onclick="return submitDNC();" />

Explanation 说明

The return value of an event handler determines whether or not the default browser behaviour should take place as well. 事件处理程序的返回值确定默认浏览器行为是否也应发生。 In the case of clicking on links, this would be following the link, but the difference is most noticeable in form submit handlers, where you can cancel a form submission if the user has made a mistake entering the information. 在单击链接的情况下,将在该链接之后,但是在表单提交处理程序中最明显的区别是,如果用户输入信息有误,则可以取消表单提交。


Another Option 另外一个选项

As Rink says, return false; 正如Rink所说, return false; 否则 return false; is overkill for something that can and should be handled by preventDefault() . 对于某些可以并且应该由preventDefault()处理的事情来说,这是过分的杀伤力。 So, you can do this way, by using unobtrusive JavaScript. 因此,您可以使用不引人注目的JavaScript来做到这一点。

function submitDNC()
{
    alert("Hello World!");
    var e = window.event;
    e.preventDefault();
}

To prevent submit when pressing ENTER, use this piece of code: 为了防止在按ENTER时提交,请使用以下代码:

function checkEnter(e){
    e = e || event;
    var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
    return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}

then, add the handler to the form : 然后,将处理程序添加到以下form

document.querySelector('form').onkeypress = checkEnter;

I would change the to a Submit, although this isn't what's getting you in trouble here. 我将更改为Submit,尽管这不是让您在这里遇到麻烦的原因。 For some odd reason browser programmers thought it was a good idea to code so that browsers assume buttons within forms submit them. 由于某些奇怪的原因,浏览器程序员认为编码是一个好主意,以便浏览器假定表单中的按钮提交它们。 You'll want to change onkeypress to call a function. 您将需要更改onkeypress来调用函数。 In that function do something like this: 在该函数中执行以下操作:

function keyPressPhone() {
  if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
    document.getElementById("addDNCform").submit();
    return true;
  }
  else {
    return false; // somehow prevents the form from being submitted
  }
}

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

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