I use materialize css for my project, i have problem when i want to append option in matrialize select with ajax. I've following this answer How to dynamically modify <select> in materialize css framework. but not working.
in my html i use materialize modal for render materialize form. this my code :
<div class="input-field col s12">
<select id="select_1" name="select_1">
<option value="1">option 1</option>
<option value="2">option 2Barat</option>
</select>
<label for="select_1">Select 1</label>
</div>
<div class="input-field col s12">
<select id="select_2" name="select_2">
<option value="0" disabled="disabled">Choose option</option>
</select>
<label for="select_2">Select 2</label>
</div>
my js
<script type="text/javascript">
$(document).ready(function(){
function get_selected(){
var base_url = '<?php echo base_url() ?>';
var data = $('#select_1').val();
$.ajax({
url: ""+base_url+"admin/get_data/",
dataType: 'json',
type: "POST",
data:{'data':data},
beforeSend: function() {
},
success: function (data) {
var text = '';
var $selectDropdown = $("#select_1").empty().html(' ');
$.each(data, function(i, val){
$selectDropdown.append($("<option></option>").attr("value",val.id).text(val.name));
})
$selectDropdown.trigger('contentChanged');
$('select').on('contentChanged', function() {
// re-initialize (update)
$(this).material_select();
});
},
error: function (xhr, status, err) {
// console.log(xhr);
// console.log(status);
// console.log(err);
},
});
}
$(document).on('change','#select_1', function(){
get_selected();
})
})
</script>
note : i using jquery 3.3.1 and materialize version 0.100.2. thank you for your help, sorry for my english :)
For anyone coming here after 2019, please note that, the API has changed and material_Select() no longer works. Use,