获取已选中的option的值,多选下拉框已选中的索引值
$('.btn-exchange').click(function(){
//获取id="select-brands"select 单选下拉框选中的索引值
var brandCode = $('#select-brands').find('option:selected').val();
//获取id="select-brands"select 单选下拉框选中的文本
var brandName = $('#select-brands').find('option:selected').text();
//获取所选下拉框brandCodeList 选中的所有option索引值(要获取所有的将':selected' 去掉即可)
var all = new Array();
$("#brandCodeList option:selected").each(function () {
var val = $(this).val();
all.push(val);
});
//判断当选选中的select-brands的索引值是否在brandCodeList中已存在
var isExist = all.indexOf(brandCode);
if (isExist >= 0) {
alert('关联品牌:"'+brandName+'"已存在,不能重复添加!');
return false;
}
//不存在将选中的select-brands的索引值添加到brandCodeList中
$('#brandCodeList ').append(`<option value="\${brandCode}" selected>\${brandName}</option>`).trigger('change');
});
页面效果:
获取多选的下拉框已选中的option个数:
$('.btn-save').on('click', function() {
//获取所有的option的个数
var brandLengthAll = $('#brandCodeList option').length;
//获取已选中的option个数
var brandCodeLength = $('#brandCodeList option:selected').length;
if (brandCodeLength < 5) {
alert('最少需要添加5个关联品牌');
return false;
}
})