I'm adding new options to select tag and I don't want any of them to be selected. I've tried a couple of ways to do it but every time first option is selected. Here's code:
const $selectField = $('.clsname');
const array = ['option1', 'option2', 'option3'];
$selectField.empty();
array.forEach(function(iter, elem) {
$selectField.append(new Option(iter, elem, false, false));
});
$selectField.show();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select hidden class="clsname"></select>
As far as I understand using new Option()
with defaultSelected
and selected set to false
should resolve the problem.
Additionally, I've tried adding something like this after forEach
, but it doesn't work either.
$selectField.children("option:selected").prop("selected", false);