1

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);
double-beep
  • 5,031
  • 17
  • 33
  • 41
xyz
  • 306
  • 3
  • 11
  • Is this useful: https://stackoverflow.com/questions/22033922/how-to-show-disable-html-select-option-in-by-default? – Andrew Halpern May 25 '20 at 08:27
  • If you do not want them to be selected then what are the uses of adding them? – Mamun May 25 '20 at 08:35
  • @AndrewHalpern unfortunately not – xyz May 25 '20 at 08:36
  • @Mamun I want user to select them and non of the options should be selected before he decides which one to choose – xyz May 25 '20 at 08:36
  • What about this? Setting an empty first open? https://stackoverflow.com/questions/24332437/how-to-make-select-element-not-to-choose-first-option-as-selected-by-default – Andrew Halpern May 25 '20 at 08:37

1 Answers1

1

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>
Lapskaus
  • 1,709
  • 1
  • 11
  • 22