重写jQuery serialize方法,使文本框在没有输入的情况下,使用其支持默认值
未压缩版
1 jQuery.fn.extend({ 2 serialize:function() { 3 return jQuery.param(this.serializeArray()); 4 }, 5 serializeArray:function() { 6 var rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; 7 var rcheckableType = /^(?:checkbox|radio)$/i; 8 var rtagName = /<([a-z][^\/\0>\x20\t\r\n\f]+)/i; 9 var rscriptType = /^$|\/(?:java|ecma)script/i; 10 return this.map(function() { 11 var elements = jQuery.prop(this, "elements"); 12 return elements ? jQuery.makeArray(elements) :this; 13 }).filter(function() { 14 var type = this.type; 15 return this.name && !jQuery(this).is(":disabled") && rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) && (this.checked || !rcheckableType.test(type)); 16 }).map(function(i, elem) { 17 var val = jQuery(this).val(); 18 if (val == null) { 19 return null; 20 } 21 if (val == "") { 22 if (jQuery(this).is("[default]")) { 23 val = jQuery(this).attr("default"); 24 } 25 } 26 if (Array.isArray(val)) { 27 return jQuery.map(val, function(val) { 28 return { 29 name:elem.name, 30 value:val.replace(rCRLF, "\r\n") 31 }; 32 }); 33 } 34 return { 35 name:elem.name, 36 value:val.replace(rCRLF, "\r\n") 37 }; 38 }).get(); 39 } 40 });
压缩版
jQuery.fn.extend({ serialize: function () { return jQuery.param(this.serializeArray()) }, serializeArray: function () { var rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; var rcheckableType = (/^(?:checkbox|radio)$/i); var rtagName = (/<([a-z][^\/\0>\x20\t\r\n\f]+)/i); var rscriptType = (/^$|\/(?:java|ecma)script/i); return this.map(function () { var elements = jQuery.prop(this, "elements"); return elements ? jQuery.makeArray(elements) : this }).filter(function () { var type = this.type; return this.name && !jQuery(this).is(":disabled") && rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) && (this.checked || !rcheckableType.test(type)) }).map(function (i, elem) { var val = jQuery(this).val(); if (val == null) { return null } if (val == "") { if (jQuery(this).is("[default]")) { val = jQuery(this).attr("default") } } if (Array.isArray(val)) { return jQuery.map(val, function (val) { return { name: elem.name, value: val.replace(rCRLF, "\r\n") } }) } return { name: elem.name, value: val.replace(rCRLF, "\r\n") } }).get() } });
文本框的添加属性 default
<form id="from"> <input type="input" name="name" default="test"/> </form>
使用方法
$("#form").serialize();