Reputation: 215
How do I empty a selectpicker with use of javascript? For testing purposes I have two selectpickers, html
code:
<select id="selectzvlntype" class="selectpicker show-tick" data-size="5" data-live-search="true" data-width="100%">
<option value="0" selected disabled>Kies type zorgverlener</option>
<?php
$q = "SELECT id_zvln_type, zvln_type
FROM tbl_zvln_types
ORDER BY zvln_type ASC";
$r = mysqli_query($dbc, $q);
while($zvln_types = mysqli_fetch_assoc($r)) { ?>
<option value="<?php echo $zvln_types['id_zvln_type']; ?>"><?php echo $zvln_types['zvln_type']; ?></option>
<?php } ?>
</select>
html
code of my second selectpicker:
<select class="selectpicker show-tick" data-size="5" data-live-search="true" data-width="100%" id="selectzkh" onchange="ga('send', 'event', 'Select Choice', 'Select ZKH Changed', this.options[this.selectedIndex].value]);">
<option value="0" selected disabled>Kies uw zorgverlener</option>
<?php
$q = "SELECT id_zvln, zvln
FROM tbl_zvln
ORDER BY zvln ASC";
$r = mysqli_query($dbc, $q);
while($zvln = mysqli_fetch_assoc($r)) { ?>
<option value="<?php echo $zvln['id_zvln']; ?>"><?php echo $zvln['zvln']; ?></option>
<?php } ?>
</select>
My javascript
code:
$(function() {
$('#selectzvlntype').on('change', function(){
//var selected = $(this).find("option:selected").val();
//alert(selected);
$('#selectzkh').empty();
});
});
The alert is working, so the $('#selectzvlntype').on('change', function()
is working, but the .empty();
is not..
Any help is much appreciated
Upvotes: 2
Views: 10428
Reputation: 49133
You have to bear in mind that once the selectPicker
plugin is invoked, it hides the original <select>
element and injects its own <div>
(along with more elements) to render the actual picker.
That's why calling empty()
on the original element won't work. You need to use the plugin's own methods to do that:
$('#selectzkh').selectpicker('destroy');
See Documentation
Upvotes: 0
Reputation: 1182
Selectpicker component does not refresh itself automatically when you manipulate the DOM element. You need to call $('#selectzkh').selectpicker("refresh")
method to make it work.
Upvotes: 8