Reputation: 1051
I'm going to create a simple E-commerce application. I have API call, which returns variations object like below. I want to dynamically generate variation boxes in this example my aim is to generate 2 select boxes, the first which holds all Color options and the second which holds all Value options. Right now I am receiving one option value, I want to receive options value like the image which I have referred to. In addition, the select boxes are dynamic there can be more than three variations. How can I achieve this result? Thanks in advance.
var variations = [{
NameValueList: [
{ Name: "Color", Value: ["Cloud White / Core Black"] },
{ Name: "US Shoe Size (Women's)", Value: ["11"] },
]
},
{
NameValueList: [
{ Name: "Color", Value: ["Cloud White / Core Green"] },
{ Name: "US Shoe Size (Women's)", Value: ["13"] },
]
},
{
NameValueList: [
{ Name: "Color", Value: ["Cloud White / Core White"] },
{ Name: "US Shoe Size (Women's)", Value: ["15"] },
]
},
]
document.getElementById("generateVariations").addEventListener("click", () => {
var html;
variations.map(el => {
html = el.NameValueList.map(nameValue => {
return `<select name="${nameValue.Name}">
<option value="${nameValue.Value[0]}">${nameValue.Value[0]}</option>
</select>`
})
})
document.getElementById("variations2").innerHTML = html.join('')
})
<div id="variations2"></div>
<button id="generateVariations">Generate variations</button>
Upvotes: 0
Views: 157
Reputation: 979
I'm not sure but I think is what you want.
var variations = [{
NameValueList: [{
Name: "Color",
Value: ["Cloud White / Core Black"]
},
{
Name: "US Shoe Size (Women's)",
Value: ["11"]
},
]
},
{
NameValueList: [{
Name: "Color",
Value: ["Cloud White / Core Green"]
},
{
Name: "US Shoe Size (Women's)",
Value: ["13"]
},
]
},
{
NameValueList: [{
Name: "Color",
Value: ["Cloud White / Core White"]
},
{
Name: "US Shoe Size (Women's)",
Value: ["15"]
},
]
},
]
let colors = variations.map(v => v.NameValueList[0]);
let sizes = variations.map(v => v.NameValueList[1])
document.getElementById("generateVariations").addEventListener("click", () => {
var colors_select = `<select name="${colors[0].Name}">
${colors.map(e=>{
return `<option value="${e.Value[0]}">${e.Value[0]}</option>`
}).join()}
</select>`
var sizes_select = `<select name="${sizes[0].Name}">
${sizes.map(e=>{
return `<option value="${e.Value[0]}">${e.Value[0]}</option>`
}).join()}
</select>`
document.getElementById("variations2").innerHTML = colors_select + sizes_select;
})
<div id="variations2"></div>
<button id="generateVariations">Generate variations</button>
Upvotes: 1