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);
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.