Reputation: 306
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);
Upvotes: 1
Views: 69
Reputation: 1721
You can set the value of the select field to null
after you added your options.
$('#mySelect').val(null)
for(var i = 1; i < 5; i++) {
$option = $('<option></option>').text('Option ' + i).val(i);
$('select').append($option);
}
$('select').val(null)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
</select>
Upvotes: 1