這是擴展「serializeArray」方法(同時保留原始行爲)的另一種解決方案。
//Store the reference to the original method:
var _serializeArray = $ ji.fn.serializeArray;
//Now extend it with newer "unchecked checkbox" functionality:
$ji.fn.extend({
serializeArray: function() {
//Important: Get the results as you normally would...
var results = _serializeArray.call(this);
//Now, find all the checkboxes and append their "checked" state to the results.
this.find('input[type=checkbox]').each(function (id, item) {
var $item = $ji(item);
var item_value = $item.is(":checked") ? 1 : 0;
var item_name = $item.attr('name');
var result_index = null;
results.each(function (data, index) {
if (data.name == item_name) {
result_index = index;
}
});
if (result_index != null) {
// FOUND replace previous value
results[result_index].value = item_value;
}
else {
// NO value has been found add new one
results.push({name: item_name, value: item_value});
}
});
return results;
}
});
這實際上將追加「真」或「假」布爾結果,但如果你喜歡,你可以使用分別爲「1」和「0」,由值更改爲value: $item.is(":checked") ? 1 : 0
。
使用
就像往常一樣,打電話給你的窗體上的方法:$form.serialize()
或$form.serializeArray()
。不管怎樣,serialize
總是使用serializeArray
,所以你可以用你調用的任何方法得到正確的結果(儘管格式不同)。
我們在ASP網上做的是有一個隱藏的輸入: '' '' 這種方式如果沒有勾選,它會取值爲隱藏的 – 2014-02-11 11:25:22