选中我们决定使用此代码保留的复选框
$('.list input[type=checkbox]').on('change', function () {
var favorite = {};
$('.list input[type=checkbox]:checked').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (typeof (favorite[name]) === 'undefined') {
favorite[name] = [];
}
favorite[name].push($el.val());
});
$.ajax({
url: '/Search.asp',
type: 'POST',
data: $.param(favorite),
dataType: 'text',
success: function (data) {
$("#ExSearchForm").html(data)
.find('input[type=checkbox]').each(function () {
var $el = $(this);
var name = $el.attr('name');
var value = $el.attr('value')
if (favorite[name] && favorite[name].indexOf(value) !== -1) {
$el.prop('checked', true);
}
});
}
});
});
现在我们还需要按下类似的下拉值
$('.list Select[option]').on('change', function () {
var favorite = {};
$('.list Select[option]:selected').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (typeof (favorite[name]) === 'undefined') {
favorite[name] = [];
}
favorite[name].push($el.val());
});
$.ajax({
url: '/Search.asp',
type: 'POST',
data: $.param(favorite),
dataType: 'text',
success: function (data) {
$("#ExSearchForm").html(data)
.find('Select[option]').each(function () {
var $el = $(this);
var name = $el.attr('name');
var value = $el.attr('value')
if (favorite[name] && favorite[name].indexOf(value) !== -1) {
$el.prop('selected', true);
}
});
}
});
});
可以合并到一个ajax帖子吗?
答案 0 :(得分:1)
可以通过使用常用函数 onValueChange 并将其附加为复选框和下拉列表的更改事件的侦听器来实现:
function onValueChange() {
var favorite = {};
$('.list input[type=checkbox]:checked').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (typeof (favorite[name]) === 'undefined') {
favorite[name] = [];
}
favorite[name].push($el.val());
});
$('.list Select[option]:selected').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (typeof (favorite[name]) === 'undefined') {
favorite[name] = [];
}
favorite[name].push($el.val());
});
$.ajax({
url: '/Search.asp',
type: 'POST',
data: $.param(favorite),
dataType: 'text',
success: function (data) {
$("#ExSearchForm").html(data)
.find('input[type=checkbox]').each(function () {
var $el = $(this);
var name = $el.attr('name');
var value = $el.attr('value')
if (favorite[name] && favorite[name].indexOf(value) !== -1) {
$el.prop('checked', true);
}
});
$("#ExSearchForm").html(data)
.find('Select[option]').each(function () {
var $el = $(this);
var name = $el.attr('name');
var value = $el.attr('value')
if (favorite[name] && favorite[name].indexOf(value) !== -1) {
$el.prop('selected', true);
}
});
}
});
};
$('.list input[type=checkbox]').on('change',onValueChange);
$('.list Select[option]').on('change', onValueChange);