DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> jQuery入門知識 >> JQuery特效代碼 >> jquery.form.js用法之清空form的方法
jquery.form.js用法之清空form的方法
編輯:JQuery特效代碼     

本段代碼摘取自jquery.form.js中,由於覺得該方法的使用性非常強,同時也可獨立拿出來使用。
該段代碼言簡意赅可以很好的作為學習參考。

. 代碼如下:
/**
 * Clears the form data. Takes the following actions on the form's input fields:
 * - input text fields will have their 'value' property set to the empty string
 * - select elements will have their 'selectedIndex' property set to -1
 * - checkbox and radio inputs will have their 'checked' property set to false
 * - inputs of type submit, button, reset, and hidden will *not* be effected
 * - button elements will *not* be effected
 */
$.fn.clearForm = function(includeHidden) {
    return this.each(function() {
        $('input,select,textarea', this).clearFields(includeHidden);   //this表示設置上下文環境,有多個表單時只作用調用的表單
    });
};

$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
    var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (re.test(t) || tag == 'textarea') {
            this.value = '';
        }
        else if (t == 'checkbox' || t == 'radio') {
            this.checked = false;
        }
        else if (tag == 'select') {
            this.selectedIndex = -1;
        }
        else if (t == "file") {
            if (/MSIE/.test(navigator.userAgent)) {
                 $(this).replaceWith($(this).clone(true));
            } else {
                 $(this).val('');
            }
       }
        else if (includeHidden) {
            // includeHidden can be the value true, or it can be a selector string
            // indicating a special test; for example:
            // $('#myForm').clearForm('.special:hidden')
            // the above would clean hidden inputs that have the class of 'special'
            if ( (includeHidden === true && /hidden/.test(t)) ||
                 (typeof includeHidden == 'string' && $(this).is(includeHidden)) ) {
                this.value = '';
            }
        }
    });
};

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved