I am generating a dropdown menu and I would like each option in the dropdown menu to be labelled with two strings (product name and company name) and have a serial number as a value attribute. These are each obtained from JSON (contained in a variable called list).
Here is a sample record from the JSON:
[
{
'code': '01234567',
'company': 'SAMPLE COMPANY',
'name': 'SAMPLE PRODUCT'
}
]
This should be presented in the HTML like so:
<option value="01234567">SAMPLE PRODUCT [SAMPLE COMPANY]</option>
My Javascript is as follows:
for (let i = 0; i < l; i++) {
var opt = document.createElement("OPTION");
opt.setAttribute("value", list[i]["code"]);
var product = list[i]["name"];
var company = list[i]["company"];
opt.innerHTML = product.concat(" [", company, "]");
}
However, this fails with "Uncaught TypeError: product.concat is not a function". I've checked the data type for product and company and they are both strings in all instances.
What else might be causing this type error?
// product is string type, just join them with "+"
// concat is a method of array type
opt.innerHTML = product + " [" + company + "]";
// tempalte string in ES6
opt.innerHTML = `${product} [${company}]`;
You can use template literal as
opt.innerHTML = `${product} [${company}]`;
const list = [{
'code': '01234567',
'company': 'SAMPLE COMPANY',
'name': 'SAMPLE PRODUCT'
}]
for (let i = 0; i < list.length; i++) {
var opt = document.createElement("OPTION");
opt.setAttribute("value", list[i]["code"]);
var product = list[i]["name"];
var company = list[i]["company"];
opt.innerHTML = `${product} [${company}]`;
document.body.appendChild(opt)
}