jQuery 表單應用:全選/取消全選,表單驗證,網頁選項卡切換

應用一:單行文本框應用


需要用到的 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>


效果:

wKiom1hI0ByiFwbUAAJqcOS8zfo516.gif


應用二:多行文本框應用


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>


效果:

wKioL1hI16XA1bn9AAkHxus6ps8533.gif



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>


效果:

wKioL1hI52rBYyHoABur_XYgdJI404.gif




應用三:複選框應用 


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" style="margin:50px;">
    <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 style="margin-top:10px;">
        <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>


效果:

wKiom1hI8meT6ewPAAeJPb2gEXs189.gif



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" style="margin:50px;">
    <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 style="margin-top:10px;">
        <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>


效果:

wKioL1hI90uSO3v8AAk7rBvB_4U350.gif


仔細觀察一下,其實上面的操作是有 bug的,當選中控制全選的複選框,選項組裏面只有部分選中時,這個還是全選嗎?顯然不是,我們期望只有部分選項組選中時,去掉全選框的鉤子。如下圖

wKiom1hI99HhAS5AAAAi0ddvwnQ610.png

所以還需要一段代碼來對複選框組進行操作,以通過它們來控制 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);
});


效果:

wKiom1hI_UzzXUW7AAJXAnBW-gk313.gif



應用四:下拉框應用 


需要用到的 API

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

dblclick([[data],fn])   --> 當雙擊元素時,會發生 dblclick 事件


wKioL1hI_1Hi75OFAAAQo9t5TWM467.png


如上圖,需要實現的功能如下:

(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 style="width:100px; height:160px;">
        <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" style="width: 100px;height:160px;">
        <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>


效果:

wKiom1hJBqrx-HSxABuwoB3x0_4530.gif



應用五:表單驗證


需要用到的 API

trigger(type,[data])   --> 在每一個匹配的元素上觸發某類事件

triggerHandler(type,[data])  --> 這個特別的方法將會觸發指定的事件類型上所有綁定的處理函數。但不會執行瀏覽器默認動作,也不會產生事件冒泡。


這個方法的行爲表現與trigger類似,但有以下三個主要區別: 

* 第一,他不會觸發瀏覽器默認事件。

* 第二,只觸發jQuery對象集合中第一個元素的事件處理函數。

* 第三,這個方法的返回的是事件處理函數的返回值,而不是據有可鏈性的jQuery對象。此外,如果最開始的jQuery對象集合爲空,則這個方法返回 undefined 。


有這樣一個簡單的表單頁面:

wKiom1hJCiLA85ntAAAIN4pDMqE832.png


class爲required 的文本框是必須填寫的,加一個 *用以區別

// class爲required 的文本框是必須填寫的,加一個 *用以區別
$('form :input.required').each(function(){
    //創建元素
    var required = $('<strong class="high"> *</strong>');
    //將它追加到文檔中
    $(this).parent().append( required );
});


wKiom1hJCmGiD0iQAAAJeUnrYkM694.png

驗證表單元素步驟如下:

(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>');
        }
    }
});


wKioL1hJEdCzexHkAAl1ZXs0t98859.gif


代碼總覽

<!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('images/reg3.gif') no-repeat 0 center;
            padding-left:25px;
        }
        .onSuccess{
            background:#E9FBEB url('images/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>


wKiom1hJGrCSgLdqAAJ8giGvdO8388.gif



應用六:切換選項卡


需要用到的 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>


效果:

wKioL1hJHsfi2MK7AASYx2xRvok713.gif



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章