我有一些选择下拉列表
<div class="selector">
<div class="nomination selectors-part">Year</div>
<div class="selection mini">
<select name="seltoYear">
<option selected disabled>Till</option>
<option value="2015">2015</option>
<option>2014</option>
<option>2013</option>
<option>2012</option>
<option>2011</option>
</select>
</div>
<div class="selection mini">
<select name="selfromYear">
<option selected disabled>From</option>
<option>1956</option>
<option>1986</option>
<option>1993</option>
<option>1994</option>
<option>1995</option>
<option>1996</option>
</select>
</div>
<div class="clear"></div>
</div>
我尝试在POSt之后设置选定值,但没有任何反复意见
$(function() {
$('div.list input[type=checkbox]').on('change',onValueChange);
$('div.selector select').on('change', onValueChange);
function onValueChange() {
var Checked = {};
var Selected = {};
// Hold all checkboxes
$('div.list input[type=checkbox]:checked').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (typeof (Checked[name]) === 'undefined') {
Checked[name] = [];
}
Checked[name].push($el.val());
});
// Hold all dropdowns
$('div.list select').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (typeof (Selected[name]) === 'undefined') {
Selected[name] = [];
}
Selected[name].push($el.val());
});
// Put all together to POST
$.ajax({
url: '/Search.asp',
type: 'POST',
data: $.param(Checked) + "&" + $.param(Selected),
dataType: 'text',
success: function (data) {
$("#ExSearchForm").html(data)
.find('div.list input[type=checkbox],div.selector select').each(function () {
var $el = $(this);
var name = $el.attr('name');
var value = $el.attr('value');
if (Checked[name] && Checked[name].indexOf(value) !== -1) {
$el.prop('checked', true);
}
if (Selected[name] && Selected[name].indexOf(value) !== -1) {
$el.prop('selected', true);
}
});
}
});
};
});
复选框也在选择,但不希望选择下拉列表。
答案 0 :(得分:2)
要设置选择元素,您必须使用val()
之类的
if (Selected[name] && Selected[name].indexOf(value) !== -1) {
$el.val(value);
}
注意,您计算value
的方式不起作用,因为您的select
元素没有value
的属性
请参阅Set selected option of select box
<强>更新强>
更改
$('div.list select').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (typeof (Selected[name]) === 'undefined') {
Selected[name] = [];
}
Selected[name].push($el.val());
});
到
$('div.list select').each(function () {
var $el = $(this);
var name = $el.attr('name');
Selected[name] = $el.val();
});
和
if (Selected[name] && Selected[name].indexOf(value) !== -1) {
$el.prop('selected', true);
}
到
if (Selected[name]) {
$el.val(Selected[name]);
}
答案 1 :(得分:0)
试试这个,
if (Selected[name] && Selected[name].indexOf(value) !== -1) {
$el.attr('selected', 'selected');
}