javascript 检查表单是否成功提交html5

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23268190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:39:39  来源:igfitidea点击:

check if form is submitted successfully html5

javascriptjqueryajaxhtmlforms

提问by Junaid Atique

I have following code.

我有以下代码。

<div class="form-group">
    <label for="store_account_name">Store Title</label>
    <input type="text" value="" class="form-control" name="store_account_name" id="store_account_name" placeholder="Please insert store title of the external store" required />
</div>
<div class="form-group">
    <label for="store_url">Store URL</label>
    <input type="url" value="" class="form-control" name="store_url" id="store_url" placeholder="Please insert store URL as described in help section" required />
</div>

On submit button I want to check if form is validated. I have an listner event which has preventDefault button. So I want to send ajax call only when both of these inputs are successfully validated. Is there any JS function to check the status of validation or any css property is add to invalid field.

在提交按钮上,我想检查表单是否经过验证。我有一个带有 preventDefault 按钮的侦听器事件。所以我想只有在这两个输入都成功验证时才发送 ajax 调用。是否有任何 JS 函数来检查验证状态或将任何 css 属性添加到无效字段。

回答by MrCode

You should use the form's onsubmitevent. It sounds like you are listening on the submit button's click event which isn't right.

您应该使用表单的onsubmit事件。听起来您正在侦听提交按钮的点击事件,这是不对的。

The form's submit event will only fire if the form is valid. The HTML5 validation rules will prevent this event from firing if the form is invalid.

表单的提交事件只会在表单有效时触发。如果表单无效,HTML5 验证规则将阻止触发此事件。

jsFiddle demo

jsFiddle 演示

$('#myform').submit(function(e){
    e.preventDefault();

    // do ajax now
    console.log("submitted"); 
});

回答by halkujabra

Based on your comment, I think this is what you are looking for-

根据您的评论,我认为这就是您要寻找的-

on 'onsubmit' attribute of 'form' call a function. In that function, do the validation, and then make an ajax call if the fields are valid, otherwise don't.

在“ onsubmit”的“ ”属性上form调用函数。在该函数中,进行验证,然后在字段有效时进行 ajax 调用,否则不进行。

回答by user7767814

try this function:

试试这个功能:

    $("input[type='submit']").click(function () {
    var form = $(this).parents("form:first");
    form.submit(function () {
        //  submitted successfully
    });
});

回答by scripter

If you would use php and json for your plan it would be clear and answering fine like other great projects. if form submittet redponse to clients the results if not throw an error via json.

如果您将 php 和 json 用于您的计划,它会很清楚并且像其他伟大的项目一样回答得很好。if form submittet redponse 给客户结果如果不通过json抛出错误。