I am writing a Laravel project where I need populate select options using jquery but when I append the options are not added. Have googled related problems, but their solution did not work for me
HTML CODE
<div class="input-field">
<select name="subCategory" id="subcategory">
<option value="" disabled selected>Select product sub-category</option>
</select>
</div>
Jquery
<script>
$(document).ready(function () {
var jsonArray = [
{
"id" : "1" ,
"name" : "item1",
"description" : "item 1 description"
},
{
"id" : "2" ,
"name" : "item2",
"description" : "item 2 description"
},
{
"id":"3" ,
"name" : "item3",
"description":"item 3 description"
},{
"id":"4" ,
"name" : "item4",
"description":"item 4 description"
},
{
"id": "5" ,
"name" : "item5",
"description":"item 5 description"
}
];
$.each(jsonArray , (key , value)=> {
console.log(value)
$('#subcategory').append("<option>"+value.name+"</option>")
})
});
</script>
If you are using materialize CSS framework make sure you initialize the select again, after appending new options. This worked for me
$.each(jsonArray , (key , value)=>{
var option = new Option(value.name , value.id)
$('#subcategory').append(option)
})
$('select').formSelect();