jQuery如何一次性验证表单,而不是一个一个验证

查看:90
本文介绍了jQuery如何一次性验证表单,而不是一个一个验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

下面的代码是在什么都不填的情况下,当点击按钮后就一个一个提示没填,但是我想要让他一次性显示哪些没填,麻烦大家给个思路

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js" type="text/javascript"></script>
<style>
.tips{ display:none;}
</style>
<script>
function check(obj)
{
    if($(obj).val()=="")
    {
        $(obj).parent().siblings().find(".tips").show();
        return false;
    }
    else
    {
        $(obj).parent().siblings().find(".tips").hide();
        return true;
    }        
}
function checkAll()
{
    if(!check("#txtName"))
    {
        return false;
    }
    else if(!check("#txtRemain"))
    {
        return false;
        }
    else if(!check("#txtDw"))
    {
        return false;
        }
    else if(confirm("确认添加?"))
    {
        return true;
    }
}
</script>
</head>

<body>
<table>
    <tr>
        <td width="33%">设备名称:</td>
        <td width="33%" class="con">
        <input type="text" id="txtName" onblur="check(this)" />
        <span class="xh">*</span></td>
        <td width="33%"><span class="tips tips1">请输入设备名称!</span></td>
    </tr>
    <tr>
        <td>设备编号:</td>
        <td class="con"><input type="text" id="txtNum" /></td>
        <td></td>
    </tr>
    <tr>
        <td>设备数量:</td>
        <td class="con"><input type="text" id="txtRemain" onblur="check(this)" /><span class="xh">*</span></td>
        <td><span class="tips tips2">请输入设备数量!</span></td>
    </tr>
    <tr>
        <td>设备单位:</td>
        <td class="con"><input type="text" id="txtDw" onblur="check(this)" /><span class="xh">*</span></td>
        <td><span class="tips tips3">请输入设备单位!</span></td>
    </tr>
    
    <tr>
        <td colspan="3" align="center">
        <input type="button" onclick="checkAll()" value="添加"/>
            
        </td>
    </tr>
    </table>
</body>
</html>

解决方案

if(!check("#txtName") || !check("#txtRemain") || !check("#txtDw"))
    {
        return false;
    }

confirm("确认添加?") 的代码应该放到外面,checkAll就应该只做check工作

=================更新的分割线===================
写完之后感觉不太安心,仔细想了想果然:||的话,如果第一个结果为true,后面的条件都不会执行的,我上面的写法,依然只能显示第一个校验。

function checkAll() {
    var checkArr = [check("#txtName"), check("#txtRemain"), check("#txtDw")];
    return checkArr.every(function (ele) {
      return ele == true;
    })
  }

这篇关于jQuery如何一次性验证表单,而不是一个一个验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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