util-1.表單相關操作(formUtil)

/**
 * ========================表單操作========================
 */
var formUtil = function(){
    /**
     * 表單序列化:serialize()方法通過序列化表單值,創建URL編碼文本字符串。
     * First name: <input type="text" name="FirstName" value="Bill" />
     * Last name: <input type="text" name="LastName" value="Gates" />
     * 輸出:FirstName=Bill&LastName=Gates
     */
  "serialize" : function(){
    return $("form").serialize();
  },
    /**
     * 表單序列化:serializeArray()方法通過序列化表單值來創建對象數組(名稱和值)
     * First name: <input type="text" name="FirstName" value="Bill" />
     * Last name: <input type="text" name="LastName" value="Gates" />
     * 輸出:[{"name":"FirstName","value":"Bill"},{"name":"LastName","value":"Gates"}]
     */
  "serializeArray" : function(){
    return $("form").serializeArray();
  },
    /**
     * 功能: 隱藏select中某些option(直接設置option的dipsplay:none;在android正常,ios無效)
     * 參數說明:
     * selectElem //需被控制的Select對象,
     * arrShow  //需顯示的option序號(留空則不處理) eg:[0,1,3],
     * arrHide //需隱藏的option序號(留空則不處理) eg:[2,4,6]
     * eg: toggleOptionShow($('#select2'),'',[0,1,3]);   //隱藏一,二,四
     * toggleOptionShow($('#select2'),[0,1,3],'');   //顯示一,二,四
     */
  "toggleOptionShow": function(selectElem,arrShow,arrHide){
    function arrHandle(arr,type){
      if($.isArray(arr)){
        var len=arr.length;
        for(i=0;i<len;i++){
          var optionNow=selectElem.find("option").eq(arr[i]);
          var optionP=optionNow.parent("span");
          if(type=="show"){         
            if(optionP.size()){
              optionP.children().clone().replaceAll(optionP); 
            }       
          }else{
            if(!optionP.size()){
              optionNow.wrap("<span style='display:none'></span>");
            }
          }
        }
      }
    }

    arrHandle(arrShow,"show");
    arrHandle(arrHide,"hide");
  }
}


/**
* 將指定的form表單上的input、select、textarea的數據清除,隱藏框作爲參數可選輸入true/false或者是樣式屬性
* 取自jquery.form.js插件中的清空表單功能理解,提取出來可在需要的時候獨立使用。
*/
$.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; // 正則表達式匹配type屬性
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase(); //獲取元素的type屬性和標籤
        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) {
            if ( (includeHidden === true && /hidden/.test(t)) ||
                 (typeof includeHidden == 'string' && $(this).is(includeHidden)) ) {   //true 、false或者樣式屬性
                this.value = '';
            }
        }
    });
};

/**
 * 1.select: 獲取下拉框選中文本值
 */
var hotelname = $("select[name='hotelId']").find("option:selected").text(); //js: innerText
var selecttype = $("select")[0].opitons($("select")[0].selectedIndex).getAttribute("data-type");

/**
 * 2.radio: 獲取單選框選中值
 */
$("input[name='radios']:checked").val();

/**
 * 3.radio: 設置值爲n的單選框選項爲選中項
 */
$("input:radio[value='n']").attr('checked','true');

/**
 * 4.checkbox: 是否選中
 */
$("input[type='checkbox']").attr("checked");

/**
 * checkbox: 看版本1.6+返回:"checked"或"undefined";  1.5-返回:true或false
 */
$("input[type='checkbox']").prop("checked"); //1.6+返回:true/false
$("input[type='checkbox']").is(":checked");  //所有版本: true/false

/**
 * checkbox: 獲取checkbox的checked方法
 */
$("input[type='checkbox']").is(":checked");
$("#checkbox_id").get(0).checked;
$("#checkbox_id").prop("checked");
$("#checkbox_id").attr("checked");
document.getElementById("checkbox_id").checked;

/**
 * checkbox: checkbox設置值: prop
 */
$("#checkbox_id").prop("checked","checked");
$("#checkbox_id").prop("checked",true);
$("#checkbox_id").prop({checked: true});
$("#checkbox_id").prop("checked",function(){return true;})

/**
 * checkbox: 選中事件監聽
 */
$("#checkbox_id").change(function(){
    //....
});

 

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