如果空字段如何停止表单提交? [英] how to stop form submit if empty fields?

查看:181
本文介绍了如果空字段如何停止表单提交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站仅基于一个 php 索引文件,该文件根据标题变量改变网站的内容。 www.mydomain.com/?page=contact 载入并弹出一个表单,我让用户填写。



我有一些 jQuery SHOULD 检测是否有任何缺失的字段:

  $(form)。submit(function(){
var isFormValid = true;
$ (.required)。each(function(){
if($ .trim($(this).val())==){
$(this).addClass( );
isFormValid = false;
} else {
$(this).removeClass(highlight);
}
如果(!isFormValid)alert (请填写所有必填字段(以*表示));
返回isFormValid;
});
});

但它不起作用....

解决方案

放置返回isFormValid 超出循环(否则您将一次又一次覆盖它的值) :

  $(form)。submit(function(){
var isFormValid = true;
$(。required)。each(function(){
if($ .trim($(this).val())==){
$(this).addClass (highlight);
isFormValid = false;
} else {
$(this).removeClass(highlight);
}

});

if(!isFormValid)alert(请填写所有必填字段(用*表示));
返回isFormValid; //放出循环
});


my website is based off of only one php index file that changes the contents of the site based on the header variables. www.mydomain.com/?page=contact loads and brings up a form that i am having the user fill out.

i have some jQuery that SHOULD detect if there are any missing fields:

$("form").submit(function() {
    var isFormValid = true;
    $(".required").each(function() {
        if ($.trim($(this).val()) == "") {
            $(this).addClass("highlight");
            isFormValid = false;
        } else {
            $(this).removeClass("highlight");
        }
        if (!isFormValid) alert("Please fill in all the required fields (indicated by *)");
        return isFormValid;
    });
});

but it is not working....

解决方案

Put return isFormValid out of loop (otherwise you are overwriting its value again and again):

$("form").submit(function() {
    var isFormValid = true;
    $(".required").each(function() {
        if ($.trim($(this).val()) == "") {
            $(this).addClass("highlight");
            isFormValid = false;
        } else {
            $(this).removeClass("highlight");
        }

    });

    if (!isFormValid) alert("Please fill in all the required fields (indicated by *)");
    return isFormValid; // put out of loop
});

这篇关于如果空字段如何停止表单提交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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