İsmail Hakkı Şen İsmail Hakkı Şen - 7 months ago 17
Javascript Question

jquery select dropdown items by class

I am trying to select some dropdown items which is not has

selected
class.

I have nice example on codepen. If I add
multiple="multiple"
it works well but its like normal list. I don't want

Codepen example

HTML

<select id="ddlSelect">
<option value="1">İsmail</option>
<option value="2" selected>Hakkı</option>
<option value="3" selected disabled>Şen</option>
</select>

<select id="ddlSelect2" multiple="multiple">
<option value="1">İsmail</option>
<option value="2" selected>Hakkı</option>
<option value="3" selected disabled>Şen</option>
</select>


JS

$(document).ready(function() {
$("#ddlSelect :not(option:selected)").each(function(index, value) {
console.log($(this).text());
});

$("#ddlSelect2 :not(option:selected)").each(function(index, value) {
console.info($(this).text());
});
});

Answer

Well that is because more than one element can be selected when dropdown is having multiple attribute set.

However for single select, only one value can be selected. As a workaround you can use has attribute selector here:

$("#ddlSelect :not(option[selected])").each(function(index, value) {
 console.log($(this).text());
});

Demo