В моем выпадающем меню включено несколько опций. Я выбираю эти параметры через
$("select#countries-"+ruleId+" option[value='"+ selectedValue + "']").prop("selected", "selected");
Однако, когда я делаю $("select#countries-"+ruleId).val()
он получает только последнее значение LAST. Но если я выберу их с нажатой клавишей Mac, он выберет несколько значений.
Любые подсказки?
Вот генетическая разметка окна выбора
<select multiple="" id="countries-new" class="form-control" onchange="selectCountryChanged('new')">
<option value="US">United States (5)</option>
<option value="LS">Lesotho (0)</option>
<option value="AX">Aland Islands (0)</option>
<option value="AL">Albania (0)</option>
<option value="DZ">Algeria (0)</option>
</select>
Это обработчики событий:
selectCountryChanged = function(ruleId) {
$( "select#countries-"+ruleId+" option:selected" ).each(function() {
selectedValue = $(this).val();
$("select#countries-"+ruleId+" option[value='"+ selectedValue + "']").prop("selected", "selected");
//$("select#countries-"+ruleId+" option[value='"+ selectedValue + "']").prop('disabled', true );
if (!$("#countryFlag-"+ruleId+"-"+selectedValue).length) {
templateCountryBtn = $("#templateCountryBtn").html();
$("#countryFlags-"+ruleId).append(_.template(templateCountryBtn, {ruleId: ruleId, countryCode: selectedValue}));
}
});
}
Я отменю выбор, используя эту функцию:
deselectCountry = function(ruleId, countryId) {
//$("select#countries-"+ruleId+" option[value='"+ countryId + "']").prop('disabled', false );
$("select#countries-"+ruleId+" option[value='"+ selectedValue + "']").attr("selected", false);
$("#countryFlag-"+ruleId+"-"+countryId).remove();
}
И я пытаюсь извлечь выбранное значение, используя:
countriesList = $("#countries-"+ruleId).val();
Это может быть то, что вы были после:
Демо: JSFiddle
JS:
var selectCountryChanged = function(ruleId) {
var selectVals = [];
var html="";
var select = $("select#countries-"+ruleId);
select.find(':selected').each(function(i, selected) {
selectVals.push( $(this).val() +"|" + $(this).text());
});
for (i=0, j=selectVals.length; i<j; i++) {
var sv = selectVals[i].split("|");
html += '<a href="#" class="'+ sv[0] +'" title="'+ sv[1] +'">'+sv[1]+'</a>';
}
$('#flagBtn').empty().append(html);
};
var deselectCoountry = function(ruleId, val) {
var select = $("select#countries-"+ruleId);
select.find('option[value="' + val + '"]').prop('selected', false);
};
var ruleID = 'new';
$(document)
.on('change', '#countries-new', function(){
selectCountryChanged(ruleID);
})
.on('click', '#flagBtn > a', function(){
deselectCoountry(ruleID, this.className);
$(this).remove();
});
HTML:
<select multiple="" id="countries-new" class="form-control">
<option value="US">United States (5)</option>
<option value="LS">Lesotho (0)</option>
<option value="AX">Aland Islands (0)</option>
<option value="AL">Albania (0)</option>
<option value="DZ">Algeria (0)</option>
</select>
<div id="flagBtn"></div>