Hi all.
I’ve got 2 select elements in html. The first select element has options A, B, C. Depending on the user’s selection, the second select element gets a unique set of options. These sets of options are brought in from php, which I’ve passed through to JSON like so:
var series = <?php echo json_encode($to_encode); ?>;
which produces an array of objects like this:
[ {supplier_id: "1", name: "Almonds", product_id: "1"}
, {supplier_id: "1", name: "Peanutes", product_id: "2"}
, {supplier_id: "1", name: "Pistachio", product_id: "3"}
, {supplier_id: "2", name: "Almonds", product_id: "4"}
, {supplier_id: "2", name: "Figs", product_id: "5"}
, {supplier_id: "2", name: "Walnuts", product_id: "6"}
]
This is my jQuery code: (works seamlessly! see fiddle: https://codepen.io/mslilafowler/pen/mdRegBz )
$(".array_of_orders").change(function(){
var array_of_orders = $(this).val();</option>';
var options;
$(series).each(function(index, value){
if(value.supplier_id == array_of_orders){
options += '<option value="'+value.product_id+'">'+value.name+'</option>';
}
});
$('.array_of_products').html(options);
});
I’ve always sucked at DOM and traversing. This is my best try, but it’s completely jumbled and producing undefined values:
document.querySelector(".array_of_orders").addEventListener("change", (e) => {
e = document.querySelector(".array_of_orders");
var array_of_orders = e.value;
var options;
// var obj = JSON.parse(series);
var obj = series;
var sel = document.querySelector('.array_of_products');
obj.forEach( function(user){
let opt = document.createElement('option');
opt.value=series.product_id;
opt.innerHTML += series.name
sel.appendChild(opt);
});
console.log(array_of_orders);
});
Any help would be great.