for my project I'm trying to create a dynamic product sheet and by now I can't fill the field from my JSON.
Here's my JS
//Creating Select
const createOptionField = document.createElement("select")
createOptionField.id = 'select-options'
createOptionField.classList.add("product-options", "product-sheet-infos")
createContainer.appendChild(createOptionField)
//Generating Option
const createOption = document.createElement('option')
createOption.value = "default"
createOptionField.appendChild(createOption)
//Fill options with JSON array
const select = document.getElementById("select-options")
const options = article.lenses
for(var i=0; i<options.lenght; i )
{
var option = document.createElement("Option"),
inner = document.createTextNode(options[i])
option.appendChild(inner);
select.insertBefore(option,select.lastChild)
}
Here's my array within my Json
Array(3) [ "50mm 1.8", "60mm 2.8", "24-60mm 2.8/4.5" ]
I don't have any error in my console and I don't know where the issue's coming from
CodePudding user response:
you can check this it should help in your situation working demo
var selectEl = document.querySelector(".select"),
data = ["one","two","three"]
loadFromJson(selectEl,data)
function loadFromJson(el,json){
// appending options from json
json.forEach(each=>{
var newEl = document.createElement("option")
newEl.innerText = each
newEl.value = each
el.appendChild(newEl)
})
}
CodePudding user response:
Hy Michel, I have done some modifications to your code. and its working fine.
You just need to do some correction in loop and options.length
const createOptionField = document.createElement("select")
createOptionField.id = 'select-options'
createOptionField.classList.add("product-options", "product-sheet-infos")
// use your container createContainer
document.getElementById("demo").appendChild(createOptionField)
//Generating Option
const createOption = document.createElement('option');
createOption.value = "default";
createOption.text='default';
createOptionField.appendChild(createOption);
//Fill options with JSON array
const select = document.getElementById("select-options")
// consider this as your array
const options = [ "50mm 1.8", "60mm 2.8", "24-60mm 2.8/4.5" ];
for(var i=0; i< options.length; i ){
//Createing single option with text and value
var option = document.createElement("option");
option.value = options[i];
option.text= options[i];
select.insertBefore(option,select.lastChild)
}