当前位置:首页 > 文章列表 > 文章 > 前端 > jQuery验证Bootstrap表格输入项

jQuery验证Bootstrap表格输入项

2025-09-14 19:09:46 0浏览 收藏

本文主要介绍如何扩展 jQuery 验证 Bootstrap 表格的功能,使其能够验证非文本输入框,如日期选择器和下拉菜单,解决默认情况下 jQuery 脚本可能只针对文本输入框进行验证的问题。通过修改 jQuery 选择器,例如将`input[type="text"]`修改为`input[type="text"], input[type="date"], select`,可以确保所有类型的输入框在提交时都经过验证,并在验证失败时提供视觉反馈,例如添加错误class,使边框颜色变化。文章提供详细的代码示例,展示如何在 Bootstrap 表格中应用修改后的 jQuery 代码,并强调了选择器扩展性、验证逻辑、用户体验和动态添加元素等注意事项,旨在帮助开发者构建更完善、用户体验更佳的 Bootstrap 表格验证功能。

使用 jQuery 验证 Bootstrap 表格中非文本输入框

本文介绍了如何使用 jQuery 扩展现有的 Bootstrap 表格验证功能,使其能够正确地验证非文本输入框(如日期选择器和下拉菜单)。通过修改 jQuery 选择器,可以确保所有类型的输入框在提交时都经过验证,并提供相应的视觉反馈。

在 Bootstrap 表格中,经常需要验证用户输入的数据,确保数据的完整性和准确性。默认情况下,一些 jQuery 脚本可能只针对文本输入框进行验证,而忽略了其他类型的输入框,例如日期选择器 (<input type="date">) 和下拉菜单 (<select>)。本文将介绍如何修改 jQuery 代码,使其能够同时验证文本和非文本输入框,并在验证失败时提供相应的视觉反馈。

修改 jQuery 选择器

问题的核心在于 jQuery 选择器的范围。原始代码只选择了 input[type="text"],这意味着只有文本类型的输入框会被验证。要解决这个问题,需要修改选择器,使其包含所有需要验证的输入框类型。

以下是修改后的代码片段:

// Add row on add button click
$(document).on("click", ".add", function(){
    var empty = false;
    var input = $(this).parents("tr").find('input[type="text"], input[type="date"], select');
    input.each(function(){
        if(!$(this).val()){
            $(this).addClass("error");
            empty = true;
        } else{
            $(this).removeClass("error");
        }
    });
    $(this).parents("tr").find(".error").first().focus();
    if(!empty){
        input.each(function(){
            $(this).parent("td").html($(this).val());
        });         
        $(this).parents("tr").find(".add, .edit").toggle();
        $(".add-new").removeAttr("disabled");
    }       
});

在这个修改后的代码中,.find() 方法现在使用了一个更广泛的选择器:'input[type="text"], input[type="date"], select'。这意味着 jQuery 将会选择所有类型为 "text" 或 "date" 的 input 元素,以及所有的 select 元素。

示例代码

以下是一个完整的示例,展示了如何将修改后的 jQuery 代码应用到 Bootstrap 表格中:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap Table with Add and Delete Row Feature</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto|Varela+Round|Open+Sans">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <style>
        body {
            color: #404E67;
            background: #F5F7FA;
            font-family: 'Open Sans', sans-serif;
        }
        .table-wrapper {
            width: 700px;
            margin: 30px auto;
            background: #fff;
            padding: 20px;
            box-shadow: 0 1px 1px rgba(0,0,0,.05);
        }
        .table-title {
            padding-bottom: 10px;
            margin: 0 0 10px;
        }
        .table-title h2 {
            margin: 6px 0 0;
            font-size: 22px;
        }
        .table-title .add-new {
            float: right;
            height: 30px;
            font-weight: bold;
            font-size: 12px;
            text-shadow: none;
            min-width: 100px;
            border-radius: 50px;
            line-height: 13px;
        }
        .table-title .add-new i {
            margin-right: 4px;
        }
        table.table {
            table-layout: fixed;
        }
        table.table tr th, table.table tr td {
            border-color: #e9e9e9;
        }
        table.table th i {
            font-size: 13px;
            margin: 0 5px;
            cursor: pointer;
        }
        table.table th:last-child {
            width: 100px;
        }
        table.table td a {
            cursor: pointer;
            display: inline-block;
            margin: 0 5px;
            min-width: 24px;
        }
        table.table td a.add {
            color: #27C46B;
        }
        table.table td a.edit {
            color: #FFC107;
        }
        table.table td a.delete {
            color: #E34724;
        }
        table.table td i {
            font-size: 19px;
        }
        table.table td a.add i {
            font-size: 24px;
            margin-right: -1px;
            position: relative;
            top: 3px;
        }
        table.table .form-control {
            height: 32px;
            line-height: 32px;
            box-shadow: none;
            border-radius: 2px;
        }
        table.table .form-control.error {
            border-color: #f50000;
        }
        table.table td .add {
            display: none;
        }
    </style>
    <script>
        $(document).ready(function(){
            $('[data-toggle="tooltip"]').tooltip();
            var actions = $("table td:last-child").html();
            // Append table with add row form on add new button click
            $(".add-new").click(function(){
                $(this).attr("disabled", "disabled");
                var index = $("table tbody tr:last-child").index();
                var row = '<tr>' +
                    '<td>&lt;input type=&quot;text&quot; class=&quot;form-control&quot; name=&quot;name&quot; id=&quot;name&quot;&gt;</td>' +
                    '<td>&lt;input type=&quot;text&quot; class=&quot;form-control&quot; name=&quot;department&quot; id=&quot;department&quot;&gt;</td>' +
                    '<td>&lt;input type=&quot;date&quot; class=&quot;form-control&quot; name=&quot;date&quot; id=&quot;date&quot;&gt;</td>' +
                    '<td>&lt;select class=&quot;form-control&quot; name=&quot;status&quot; id=&quot;status&quot;&gt;<option value="active">Active</option><option value="inactive">Inactive</option>&lt;/select&gt;</td>' +
                    '<td>' + actions + '</td>' +
                    '</tr>';
                $("table").append(row);
                $("table tbody tr").eq(index + 1).find(".add, .edit").toggle();
                $('[data-toggle="tooltip"]').tooltip();
            });
            // Add row on add button click
            $(document).on("click", ".add", function(){
                var empty = false;
                var input = $(this).parents("tr").find('input[type="text"], input[type="date"], select');
                input.each(function(){
                    if(!$(this).val()){
                        $(this).addClass("error");
                        empty = true;
                    } else{
                        $(this).removeClass("error");
                    }
                });
                $(this).parents("tr").find(".error").first().focus();
                if(!empty){
                    input.each(function(){
                        $(this).parent("td").html($(this).val());
                    });
                    $(this).parents("tr").find(".add, .edit").toggle();
                    $(".add-new").removeAttr("disabled");
                }
            });
            // Edit row on edit button click
            $(document).on("click", ".edit", function(){
                $(this).parents("tr").find("td:not(:last-child)").each(function(){
                    $(this).html('&lt;input type=&quot;text&quot; class=&quot;form-control&quot; value=&quot;&apos; + $(this).text() + &apos;&quot;&gt;');
                });
                $(this).parents("tr").find(".add, .edit").toggle();
                $(".add-new").attr("disabled", "disabled");
            });
            // Delete row on delete button click
            $(document).on("click", ".delete", function(){
                $(this).parents("tr").remove();
                $(".add-new").removeAttr("disabled");
            });
        });
    </script>
</head>
<body>
<div class="container">
    <div class="table-wrapper">
        <div class="table-title">
            <div class="row">
                <div class="col-sm-8"><h2>Employee <b>Details</b></h2></div>
                <div class="col-sm-4">
                    <button type="button" class="btn btn-info add-new"><i class="fa fa-plus"></i> Add New</button>
                </div>
            </div>
        </div>
        <table class="table table-bordered">
            <thead>
            <tr>
                <th>Name</th>
                <th>Department</th>
                <th>Date</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td>John Doe</td>
                <td>Administration</td>
                <td>2023-10-26</td>
                <td>Active</td>
                <td>
                    <a class="add" title="Add" data-toggle="tooltip"><i class="material-icons">&#xE03B;</i></a>
                    <a class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons">&#xE254;</i></a>
                    <a class="delete" title="Delete" data-toggle="tooltip"><i class="material-icons">&#xE872;</i></a>
                </td>
            </tr>
            <tr>
                <td>Peter Parker</td>
                <td>Customer Service</td>
                <td>2023-10-27</td>
                <td>Inactive</td>
                <td>
                    <a class="add" title="Add" data-toggle="tooltip"><i class="material-icons">&#xE03B;</i></a>
                    <a class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons">&#xE254;</i></a>
                    <a class="delete" title="Delete" data-toggle="tooltip"><i class="material-icons">&#xE872;</i></a>
                </td>
            </tr>
            <tr>
                <td>Fran Wilson</td>
                <td>Human Resources</td>
                <td>2023-10-28</td>
                <td>Active</td>
                <td>
                    <a class="add" title="Add" data-toggle="tooltip"><i class="material-icons">&#xE03B;</i></a>
                    <a class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons">&#xE254;</i></a>
                    <a class="delete" title="Delete" data-toggle="tooltip"><i class="material-icons">&#xE872;</i></a>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>

在这个示例中,我们添加了一个日期输入框和一个下拉菜单,并修改了 jQuery 代码来验证这些输入框。如果用户尝试添加一个空的日期或未选择下拉菜单选项,相应的输入框的边框将会变成红色,提示用户输入有效的数据。

注意事项

  • 选择器扩展性: 根据实际需求,可以进一步扩展选择器,以包含其他类型的输入框,例如 textarea、checkbox 等。
  • 验证逻辑: !$(this).val() 只检查输入框是否为空。对于更复杂的验证需求,例如日期格式验证或数值范围验证,需要添加额外的验证逻辑。
  • 用户体验: 除了边框颜色变化,还可以考虑添加更友好的错误提示信息,例如在输入框下方显示错误消息。
  • 动态添加的元素: 如果通过 AJAX 等方式动态添加新的输入框,需要确保 jQuery 代码能够正确地绑定到这些新元素上。可以使用 $(document).on() 来处理动态添加的元素。

总结

通过修改 jQuery 选择器,可以轻松地扩展 Bootstrap 表格的验证功能,使其能够验证各种类型的输入框。这有助于确保数据的完整性和准确性,并提供更好的用户体验。在实际应用中,可以根据具体需求进行定制,以满足不同的验证需求。

本篇关于《jQuery验证Bootstrap表格输入项》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!

交管12123随手拍奖励怎么领交管12123随手拍奖励怎么领
上一篇
交管12123随手拍奖励怎么领
Plotly.js树状图结构解析与使用教程
下一篇
Plotly.js树状图结构解析与使用教程
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    543次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    514次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    499次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • SEO  AI Mermaid 流程图:自然语言生成,文本驱动可视化创作
    AI Mermaid流程图
    SEO AI Mermaid 流程图工具:基于 Mermaid 语法,AI 辅助,自然语言生成流程图,提升可视化创作效率,适用于开发者、产品经理、教育工作者。
    477次使用
  • 搜获客笔记生成器:小红书医美爆款内容AI创作神器
    搜获客【笔记生成器】
    搜获客笔记生成器,国内首个聚焦小红书医美垂类的AI文案工具。1500万爆款文案库,行业专属算法,助您高效创作合规、引流的医美笔记,提升运营效率,引爆小红书流量!
    467次使用
  • iTerms:一站式法律AI工作台,智能合同审查起草与法律问答专家
    iTerms
    iTerms是一款专业的一站式法律AI工作台,提供AI合同审查、AI合同起草及AI法律问答服务。通过智能问答、深度思考与联网检索,助您高效检索法律法规与司法判例,告别传统模板,实现合同一键起草与在线编辑,大幅提升法律事务处理效率。
    497次使用
  • TokenPony:AI大模型API聚合平台,一站式接入,高效稳定高性价比
    TokenPony
    TokenPony是讯盟科技旗下的AI大模型聚合API平台。通过统一接口接入DeepSeek、Kimi、Qwen等主流模型,支持1024K超长上下文,实现零配置、免部署、极速响应与高性价比的AI应用开发,助力专业用户轻松构建智能服务。
    532次使用
  • 迅捷AIPPT:AI智能PPT生成器,高效制作专业演示文稿
    迅捷AIPPT
    迅捷AIPPT是一款高效AI智能PPT生成软件,一键智能生成精美演示文稿。内置海量专业模板、多样风格,支持自定义大纲,助您轻松制作高质量PPT,大幅节省时间。
    466次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码