我正在尝试在多个select元素的选定选项中添加一个类。我的代码正在添加新类时工作,但是,在提交时,我将获得所选最后一个选项的值。
基本上使用多个select属性进行正常选择。如果我删除添加新类的整个代码,则多重选择正在工作。
我做错了什么?
var selects = $('#pwpusform select[multiple="multiple"]');
$(selects).each(function() {
$(this).change(function() {
var SelecteD = $(this).find('option').filter(':selected');
$(SelecteD).each(function() {
$(this).addClass('optionselected');
});
}).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
For this HTML, I am getting the value of the option 5 which is selected at last.
<br/>
<select name="scattrmselect[]" class="pwpus-select-input" multiple="multiple">
<option value="10" class="optionselected">Select 1</option>
<option value="20">Select 2</option>
<option value="30" selected="selected" class="optionselected">Select 3</option>
<option value="40">Select 4</option>
<option value="50" class="optionselected">Select 5</option>
</select>
答案 0 :(得分:0)
这样的事情怎么样:
$(".pwpus-select-input").change(function(){
var options = $(this).find('option').filter(':selected');
$(options).each(function(i,item){
$(item).removeClass("optionselected").addClass("optionselected");
});
});
答案 1 :(得分:0)
我不确定你在问什么。这对我有用,所以看看你的控制台
$(function() {
$('#pwpusform select[multiple="multiple"]').each(function() {
$(this).change(function() {
var sels = []; // debug
$(this).find("option").removeClass("optionselected");
var SelecteD = $(this).find('option:selected');
$(SelecteD).each(function() {
sels.push(this.value); // debug
$(this).addClass('optionselected');
});
// debugging shows all selected options are available
$("#sel").html(sels.join(",")+"<br/>"+$('#pwpusform').serialize());
}).change();
});
});
.optionselected { text-decoration:underline }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<br/>
<form id="pwpusform">
<select name="scattrmselect[]" class="pwpus-select-input" multiple="multiple">
<option value="10" class="optionselected">Select 1</option>
<option value="20">Select 2</option>
<option value="30" selected="selected" class="optionselected">Select 3</option>
<option value="40">Select 4</option>
<option value="50" class="optionselected">Select 5</option>
</select>
</form>
<span id="sel"></span>