Reputation: 1452
I have a Bootstrap-Select dropdown which is being populated from another source upon entering a certain string into a text input. Everything works up to the point where the first option is being selected by default and I want to prevent this so the user has to select an option.
Please see a demo here: https://jsfiddle.net/moxxah8r/
Code is as follows:
<style>
.form-control,
.selectpicker {
width: 220px;
}
#postalcode {
text-transform: uppercase;
margin-right: 10px;
}
</style>
<div style="padding: 10px;">
<div style="display: flex;">
<input name="postalcode" id="postalcode" type="text" class="form-control" autocomplete="postal-code">
<select name="address" id="address" class="selectpicker" disabled>
<option value="0" selected> </option>
</select>
</div>
</div>
<script>
var data = ["1 Street Name", "2 Street Name", "3 Street Name", "4 Street Name", "5 Street Name"];
$('#postalcode').on('input', function(e) {
var pattern = new RegExp('^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$');
var text = $('#postalcode').val().toUpperCase();
if (pattern.test(text)) {
$('#address').empty();
$.each(data, function(i, value) {
$('#address').append($('<option>').text(value).attr('value', value));
});
$('#address option').prop('selected', false);
$('#address').prop('disabled', false);
$('#address').selectpicker('refresh');
} else {
$('#address').empty().append('<option value="0" selected> </option>');
$('#address').prop('disabled', true);
$('#address').selectpicker('refresh');
}
});
</script>
Upvotes: 0
Views: 4743
Reputation: 6967
The first thing you need to do is remove selected
from your pre-defined <option>
as that creates the problem by design, rather than by default.
Instead of relying on a blank <option>
hack, why not make use of some of the built-in features of Bootstrap Select? By specifying a title
in the <select>
element you can create a pseudo-placeholder. This prevents the first item in the dropdown menu from being selected by default:
<select name="address" id="address" class="selectpicker" title="Make Your Selection" disabled>...</select>
You can read about this feature as well as several other labeling options at Bootstrap Select's documentation for Custom Button Text
https://silviomoreto.github.io/bootstrap-select/examples/#placeholder
Upvotes: 2
Reputation: 152
You can do this with jQuery. Remove any blank option tag and call this on your event:
$('select#address').val([]);
Upvotes: 0