jQuery 表单应用:全选/取消全选,表单验证,网页选项卡切换

2023-05-26,,

应用一:单行文本框应用


需要用到的 API

focus([[data],fn])   --> 当元素获得焦点时,触发 focus 事件

blur([[data],fn])     --> 当元素失去焦点时,触发 blur 事件

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .focus{
            border:1px solid #f00;
            background:#fcc;
        }
    </style>
</head>
<body>
<form action="" method="post" id="myForm">
    <fieldset>
        <legend>个人基本信息</legend>
        <div>
            <label for="userName">用户姓名:</label>
            <input type="text" id="userName">
        </div>
        <div>
            <label for="cellPhone">手机号码:</label>
            <input type="text" id="cellPhone">
        </div>
        <div>
            <label for="address">联系地址:</label>
            <textarea id="address" cols="30" rows="10"></textarea>
        </div>
    </fieldset>
</form>

<script src="js/jquery-1.8.3.min.js"></script>
<script>
    $(function(){
        $(':input').focus(function(){
            $(this).addClass('focus');
        }).blur(function(){
            $(this).removeClass('focus');
        })
    })
</script>
</body>
</html>

效果:


应用二:多行文本框应用


1、高度变化

有一些网站的评论框上面有“+”和“-”按钮,它们的功能就是用来控制评论框的高度。例如单击“-”按钮,评论框的高度将会缩小。


需要用到的 API

is(expr|obj|ele|fn)   --> 根据选择器、DOM元素或 jQuery对象来检测匹配元素集合,如果其中至少有                                        一个元素符合这个给定的表达式就返回 true

:animated   --> 匹配所有正在执行动画效果的元素

animate(params,[speed],[easing],[fn])     --> 用于创建自定义动画的函数

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .msg{width:300px; margin:100px;}
        .msg_caption{width:100%;overflow:hidden;}
        .msg_caption span{display:inline-block; margin:0 2px; padding:4px 10px; background:#898989; cursor:pointer; color:#fff;}
        .msg textarea{ width:300px; height:100px; border:1px solid #000;}
    </style>
</head>
<body>
<form action="">
    <div class="msg">
        <div class="msg_caption">
            <span class="bigger">放大</span>
            <span class="smaller">缩小</span>
        </div>
        <div class="msg_content">
            <textarea id="comment" cols="30" rows="10"></textarea>
        </div>
    </div>
</form>

<script src="js/jquery-1.8.3.min.js"></script>
<script>
    $(function(){
        //获取评论框
        var comment = $('#comment');

        //为“放大”按钮绑定单击事件
        $('.bigger').click(function(){
            //判断是否处于动画,如果处于动画过程中,则不追加动画,避免造成动画队列不必要的积累
            if(!comment.is(':animated')){
                if(comment.height() <500 ){
                    //重新设置高度,在原有的基础上加50
                    comment.animate({ height:'+=50'}, 400);
                }
            }

        });
        //为“缩小”按钮绑定单击事件
        $('.smaller').click(function(){
            //判断是否处于动画
            if(!comment.is(':animated')){
                if(comment.height() >50 ){
                    comment.animate({ height:'-=50'}, 400);
                }
            }
        });
    })
</script>
</body>
</html>


效果:



2、滚动条高度变化

有一些网站的评论框上面有“+”和“-”按钮,它们的功能就是用来控制评论框的高度。例如单击“-”按钮,评论框的高度将会缩小。


需要用到的 API

scrollTop( [val] ) --> 获取匹配元素相对滚动条顶部的偏移,此方法对可见和隐藏元素都有效

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .msg{width:300px; margin:100px;}
        .msg_caption{width:100%;overflow:hidden;}
        .msg_caption span{display:inline-block; margin:0 2px; padding:4px 10px; background:#898989; cursor:pointer; color:#fff;}
        .msg textarea{ width:300px; height:100px; border:1px solid #000;}
    </style>
</head>
<body>
<form action="">
    <div class="msg">
        <div class="msg_caption">
            <span class="up">向上</span>
            <span class="down">向下</span>
        </div>
        <div class="msg_content">
            <textarea id="comment" cols="30" rows="10">
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Doloribus fuga quae soluta vel. Ab accusamus blanditiis dolorum ea eaque libero mollitia numquam officia veniam. Assumenda distinctio molestias necessitatibus sed. Eius.
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi cum error esse tempora vel! Accusantium aliquid eveniet impedit nisi numquam odit possimus provident quas reprehenderit ut? Doloremque praesentium quisquam voluptatum!
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci architecto aut corporis cupiditate dicta ducimus facere, fugiat, fugit impedit inventore maxime, mollitia nesciunt pariatur praesentium quaerat quidem ratione repudiandae voluptas.
            </textarea>
        </div>
    </div>
</form>

<script src="js/jquery-1.8.3.min.js"></script>
<script>
    $(function(){
        //获取评论框
        var comment = $('#comment');

        //为“向上”按钮绑定单击事件
        $('.up').click(function(){
            //判断是否处于动画
            if(!comment.is(':animated')){
                comment.animate({ scrollTop:'-=50'}, 400);
            }

        });
        //为“向下”按钮绑定单击事件
        $('.down').click(function(){
            //判断是否处于动画
            if(!comment.is(':animated')){
                comment.animate({ scrollTop:'+=50'}, 400);
            }
        });
    })
</script>
</body>
</html>


效果:



应用三:复选框应用 


1、用按钮控制 全选/反选/取消全选

需要用到的 API

[attribute = value]   --> 匹配给定的属性是某个特定值的元素

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link href="http://cdn.bootcss.com/bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<form class="from" >
    <p>你喜欢的运动是:</p>
    <label class="checkbox inline">
        <input type="checkbox" name="items" value="足球"> 足球
    </label>
    <label class="checkbox inline">
        <input type="checkbox" name="items" value="篮球"> 篮球
    </label>
    <label class="checkbox inline">
        <input type="checkbox" name="items" value="羽毛球"> 羽毛球
    </label>
    <label class="checkbox inline">
        <input type="checkbox" name="items" value="乒乓球"> 乒乓球
    </label>
    <div >
        <input type="button" value="全选" id="checkAll" class="btn btn-success">
        <input type="button" value="取消全选" id="checkNo" class="btn btn-danger">
        <input type="button" value="反选" id="checkReverse" class="btn btn-inverse">
        <input type="button" value="查看" id="send" class="btn btn-info">
    </div>

</form>

<script src="js/jquery-1.8.3.min.js"></script>
<script>
    $(function(){
        //全选 --> 如果checked属性为true,说明被选中,反之,则没有选中
        $('#checkAll').click(function(){
            $('[name=items]:checkbox').attr('checked', true);
        });

        //取消全选
        $('#checkNo').click(function(){
            $('[name=items]:checkbox').attr('checked', false);
        });

        //反选  -->  遍历每一个复选框,取checked属性值的反值
        $('#checkReverse').click(function(){
            $('[name=items]:checkbox').each(function(){
                //$(this).attr('checked', !$(this).attr('checked')); 方法一
                this.checked = !this.checked; //方法二:原生DOM 操作
            });
        });

        //查看选中项的值
        $('#send').click(function(){
            var str = '您选中的是:\r\n';  // \r 回车,\n 换行,\r\n 表示回车换行
            $('[name=items]:checkbox:checked').each(function(){
                str += $(this).val() + '\r\n';
            });
            alert( str );
        });
    })
</script>
</body>
</html>


效果:



2、用复选框控制 全选/取消全选

需要用到的 API

[attribute = value]   --> 匹配给定的属性是某个特定值的元素

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link href="http://cdn.bootcss.com/bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<form class="from" >
    <p>你喜欢的运动是:
        <label class="checkbox inline">
            <input type="checkbox" name="items" value="足球" id="checkAll"> 全选/取消全选
        </label>
    </p>
    <label class="checkbox inline">
        <input type="checkbox" name="items" value="足球"> 足球
    </label>
    <label class="checkbox inline">
        <input type="checkbox" name="items" value="篮球"> 篮球
    </label>
    <label class="checkbox inline">
        <input type="checkbox" name="items" value="羽毛球"> 羽毛球
    </label>
    <label class="checkbox inline">
        <input type="checkbox" name="items" value="乒乓球"> 乒乓球
    </label>
    <div >
        <input type="button" value="查看" id="send" class="btn btn-info">
    </div>

</form>

<script src="js/jquery-1.8.3.min.js"></script>
<script>
    $(function(){
        /*      方法一: 全选/取消全选
        $('#checkAll').click(function(){
            if(this.checked){  //如果全选按钮被勾中,则全部选项设为都不选,反之则全选
                $('[name=items]:checkbox').attr('checked',true)
            }else{
                $('[name=items]:checkbox').attr('checked',false)
            }
        });
        */
        //       方法二: 原生 DOM 方法  全选按钮和选项按钮的 checked属性是一致的
        $('#checkAll').click(function(){
            $('[name=items]:checkbox').attr('checked', this.checked)
        });
        
    })
</script>
</body>
</html>


效果:


仔细观察一下,其实上面的操作是有 bug的,当选中控制全选的复选框,选项组里面只有部分选中时,这个还是全选吗?显然不是,我们期望只有部分选项组选中时,去掉全选框的钩子。如下图

所以还需要一段代码来对复选框组进行操作,以通过它们来控制 id 为“checkAll”的复选框,思路如下:

(1)、对复选框组绑定单击事件

(2)、定义一个 flag 变量,默认为 true

(3)、循环复选框组,当有没被选中的选项时,则把变量 flag 的值设置为 false

(4)、根据变量 flag 的值来设置 id 为“checkAll”复选框是否选中

   >、如果 flag 为 true,说明复选框组都被选中

   >、如果 flag 为 false,说明复选框组至少有一个没有被选中

$('[name=items]:checkbox').click(function(){ //给复选框组点击单击事件
    var flag = true;
    $(this).each(function(){  //遍历每一个复选框按钮
        if(!this.checked){ //如果当前复选框按钮的checked属性为false,也就是没有被选中
            flag = false;
        }
    });
    $('#checkAll').attr('checked', flag); //只要有一个复选框没有被选中,就把 #checked 变为false
});

除了上述思路以外,还可以用下面的方法:

(1)、对复选框组绑定单击事件

(2)、判断复选框的总数是否与选中的复选框数量相等

(3)、如果相等,则说明全部选中了,id 为“checkAll”复选框应当处于选中状态,否则处于不选中

$('[name=items]:checkbox').click(function(){
    //$(this) 复选框组
    //$(this).length   复选框的个数
    //$(this).filter(':checked')  被选中的复选框
    $('#checkAll').attr('checked', $(this).length==$(this).filter(':checked').length);
});

效果:


应用四:下拉框应用 

需要用到的 API

$(A).append(B)   --> 把A追加到B中

dblclick([[data],fn])   --> 当双击元素时,会发生 dblclick 事件



如上图,需要实现的功能如下:

(1)、将选中的选项添加给对方

(2)、将全部选项添加给对方

(3)、双击某个选项将其添加给对方


<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        div.center {
            float:left;
            text-align: center;
            margin: 10px;
        }
        span {
            display:block;
            margin:2px 2px;
            padding:4px 10px;
            background:#898989;
            cursor:pointer;
            font-size:12px;
            color:white;
        }
    </style>
</head>
<body>
<div class="center">
    <select id="selectOne" multiple >
        <option value="1">选项1</option>
        <option value="2">选项2</option>
        <option value="3">选项3</option>
        <option value="4">选项4</option>
        <option value="5">选项5</option>
        <option value="6">选项6</option>
        <option value="7">选项7</option>
    </select>
    <div>
        <span id="add">选中添加到右边&gt;&gt;</span>
        <span id="add_all" >全部添加到右边&gt;&gt;</span>
    </div>
</div>

<div class="center">
    <select multiple="multiple" id="selectTwo" >
        <option value="8">选项8</option>
    </select>
    <div>
        <span id="remove">&lt;&lt;选中删除到左边</span>
        <span id="remove_all">&lt;&lt;全部删除到左边</span>
    </div>
</div>

<script src="js/jquery-1.8.3.min.js"></script>
<script>
    $(function(){
        //将选中的选项添加给对方
        $('#add').click(function(){
            //获取选中的选项
            var options = $('#selectOne option:selected');
            //追加给对方
            options.appendTo('#selectTwo');
        });

        //将全部选项添加给对方
        $('#add_all').click(function(){
            //获取全部的选项
            var options = $('#selectOne option');
            //追加给对方
            options.appendTo('#selectTwo');
        });

        //双击某个选项将其添加给对方
        $('#selectOne').dblclick(function(){
            //获取选中的选项
            var options = $('option:selected',this);
            //追加给对方
            options.appendTo('#selectTwo');
        });

        //选中删除到左边
        $('#remove').click(function(){
            var options = $('#selectTwo option:selected');
            options.appendTo('#selectOne');
        });
        //全部删除到左边
        $('#remove_all').click(function(){
            var options = $('#selectTwo option');
            options.appendTo('#selectOne');
        });
        //双击某个选项将其添加给对方
        $('#selectTwo').dblclick(function(){
            var options = $('option:selected',this);
            options.appendTo('#selectOne');
        });
    })
</script>
</body>
</html>

效果:



应用五:表单验证

需要用到的 API

trigger(type,[data])   --> 在每一个匹配的元素上触发某类事件

triggerHandler(type,[data])  --> 这个特别的方法将会触发指定的事件类型上所有绑定的处理函数。但不会执行浏览器默认动作,也不会产生事件冒泡。

这个方法的行为表现与trigger类似,但有以下三个主要区别: 

* 第一,他不会触发浏览器默认事件。

* 第二,只触发jQuery对象集合中第一个元素的事件处理函数。

* 第三,这个方法的返回的是事件处理函数的返回值,而不是据有可链性的jQuery对象。此外,如果最开始的jQuery对象集合为空,则这个方法返回 undefined 。

有这样一个简单的表单页面:


class为required 的文本框是必须填写的,加一个 *用以区别

// class为required 的文本框是必须填写的,加一个 *用以区别
$('form :input.required').each(function(){
    //创建元素
    var required = $('<strong class="high"> *</strong>');
    //将它追加到文档中
    $(this).parent().append( required );
});

验证表单元素步骤如下:

(1)、判断当前失去焦点的元素是“用户名”还是“邮箱”,然后分别处理

(2)、如果是“用户名”,判断元素值的长度是否小于6,如果小于6,则用红色提醒用户输入不正确;反之,则用绿色提醒用户输入正确

(3)、如果是“邮箱”,判断元素的值是否符合邮箱的格式,如果不符合,则用红色提醒用户输入不正确;反之,则用绿色提醒用户输入不正确

(4)、将提醒信息追加到当前元素的父元素之后

//文本框失去焦点后
$('form :input').blur(function(){ //为表单元素添加失去焦点事件
    var parent = $(this).parent();
    //去掉先前的提醒,否则提示消息会一直叠加
    parent.find(".formtips").remove(); 
    //验证用户名
    if($(this).is('#username')){
        if(this.value == '' || this.value.length<6){
            var errorMsg = '请输入至少6位的用户名';
            parent.append('<span class="formtips onError">'+errorMsg+'</span>');
        }else{
            var okMsg = '输入正确';
            parent.append('<span class="formtips onSuccess">'+okMsg+'</span>');
        }
    }
    //验证邮箱
    if($(this).is('#email')){
        if(this.value=='' || ( this.value!='' && !/.+@.+\.[a-zA-Z]{2,4}$/.test(this.value) ) ){
            var errorMsg = '请输入正确的E-Mail地址';
            parent.append('<span class="formtips onError">'+errorMsg+'</span>');
        }else{
            var okMsg = '输入正确';
            parent.append('<span class="formtips onSuccess">'+okMsg+'</span>');
        }
    }
});


代码总览

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        body { font:12px/19px Arial, Helvetica, sans-serif; color:#666;}
        form div { margin:15px 0;}
        .int label { float:left; width:100px; text-align:right;}
        .int input { padding:1px 1px; border:1px solid #ccc;height:16px;}
        .sub { padding-left:100px;}
        .sub input { margin-right:10px; }
        .formtips{width: 200px;margin:2px;padding:2px;}
        .onError{
            background:#FFE0E9 url('p_w_picpaths/reg3.gif') no-repeat 0 center;
            padding-left:25px;
        }
        .onSuccess{
            background:#E9FBEB url('p_w_picpaths/reg4.gif') no-repeat 0 center;
            padding-left:25px;
        }
        .high{
            color:red;
        }
    </style>
</head>
<body>
<form method="post" action="">
    <div class="int">
        <label for="username">用户名:</label>
        <input type="text" id="username" class="required" />
    </div>
    <div class="int">
        <label for="email">邮箱:</label>
        <input type="text" id="email" class="required" />
    </div>
    <div class="int">
        <label for="personinfo">个人资料:</label>
        <input type="text" id="personinfo" />
    </div>
    <div class="sub">
        <input type="submit" value="提交" id="send"/><input type="reset" id="res"/>
    </div>
</form>

<script src="js/jquery-1.8.3.min.js"></script>
<script>
    $(function(){
        // class为required 的文本框是必须填写的,加一个 *用以区别
        $('form :input.required').each(function(){
            //创建元素
            var required = $('<strong class="high"> *</strong>');
            //将它追加到文档中
            $(this).parent().append( required );
        });

        //文本框失去焦点后
        $('form :input').blur(function(){ //为表单元素添加失去焦点事件
            var parent = $(this).parent();
            //去掉先前的提醒,否则提示消息会一直叠加
            parent.find(".formtips").remove();
            //验证用户名
            if($(this).is('#username')){
                if(this.value == '' || this.value.length<6){
                    var errorMsg = '请输入至少6位的用户名';
                    parent.append('<span class="formtips onError">'+errorMsg+'</span>');
                }else{
                    var okMsg = '输入正确';
                    parent.append('<span class="formtips onSuccess">'+okMsg+'</span>');
                }
            }
            //验证邮箱
            if($(this).is('#email')){
                if(this.value=='' || ( this.value!='' && !/.+@.+\.[a-zA-Z]{2,4}$/.test(this.value) ) ){
                    var errorMsg = '请输入正确的E-Mail地址';
                    parent.append('<span class="formtips onError">'+errorMsg+'</span>');
                }else{
                    var okMsg = '输入正确';
                    parent.append('<span class="formtips onSuccess">'+okMsg+'</span>');
                }
            }
        }).keyup(function(){
            $(this).triggerHandler('blur');
        }).focus(function(){
            $(this).triggerHandler('blur');
        });

        //提交,最终验证
        $('#send').click(function(){
            $('form .required:input').trigger('blur');
            var numberError = $('form .onError').length;
            if(numberError){
                return false; //只要存在这个数字就说明有错误,需要阻止表单提交
            }
            alert('注册成功,密码已发到邮箱,请查收!');
        });

        //重置
        $('#res').click(function(){
            $(".formtips").remove();
        });
    })
</script>
</body>
</html>



应用六:切换选项卡

需要用到的 API

eq(index|-index)   --> 获取第N个元素 (index从0开始)

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        *{ margin:0; padding:0;}
        body { font:12px/19px Arial, Helvetica, sans-serif; color:#666;}
        .tab { width:240px;margin:50px;}
        .tab_menu { clear:both;}
        .tab_menu li { float:left; text-align:center; cursor:pointer; list-style:none; padding:1px 6px; margin-right:4px; background:#F1F1F1; border:1px solid #898989; border-bottom:none;}
        .tab_menu li.hover { background:#DFDFDF;}
        .tab_menu li.selected { color:#FFF; background:#6D84B4;}
        .tab_box { clear:both; border:1px solid #898989; height:100px;}
        .hide{display:none}
    </style>
</head>
<body>
<div class="tab">
    <div class="tab_menu">
        <ul>
            <li class="selected">时事</li>
            <li>体育</li>
            <li>娱乐</li>
        </ul>
    </div>
    <div class="tab_box">
        <div>时事</div>
        <div class="hide">体育</div>
        <div class="hide">娱乐</div>
    </div>
</div>

<script src="js/jquery-1.8.3.min.js"></script>
<script>
    $(function(){
        var tabs = $('.tab .tab_menu ul li');
        tabs.click(function(){
            $(this).addClass('selected').siblings().removeClass('selected');
            //获取当前li 元素在全部 li 中的索引
            var index = tabs.index(this);
            //显示li元素 对应的div 元素,其余的隐藏
            $('.tab .tab_box>div').eq(index).show().siblings().hide();
        });
    })
</script>
</body>
</html>

效果:


《jQuery 表单应用:全选/取消全选,表单验证,网页选项卡切换.doc》

下载本文的Word格式文档,以方便收藏与打印。