如果出现错误,停止在jquery中提交表单 [英] Stop form submitting in jquery if an error

查看:84
本文介绍了如果出现错误,停止在jquery中提交表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码: http://jsfiddle.net/Xk38X/6/

This is my code: http://jsfiddle.net/Xk38X/6/

  $('#register').click(function()
{
    if( $('#company_f').val().length == 0 ) {
        $('#company_f').css("border", "solid 1px red");
    }
});

问题在于,即使它出错,它仍然会发送表格.谁能告诉我,如果用户单击按钮并且公司字段未填写,我将如何停止提交表单.

The issue is even when it errors it still sends the form. Can anyone please tell me how I stop it submitting the form if the user hits the button and the company field isn't filled out.

谢谢.

推荐答案

使用return false事件. preventdefault()

$('#register').click(function (e) {
    if ($('#company_f').val().length == 0) {
        $('#company_f').css("border", "solid 1px red");
        return false; // or e.preventdefault();
    }
});


更好的代码版本


A Little better version of your code

var company_f = $('#company_f'); //cache your selector
$('#register').click(function (e) {
    if (company_f.val().length == 0) {
        company_f.css("border", "solid 1px red");
        return false; // or e.preventdefault();
    }
});


还请阅读 HTML必需属性

这篇关于如果出现错误,停止在jquery中提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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