I am trying to create some html elements with template literals. I know I could have a for loop and create the options one by one but I find that to be messy code. This is the best way that I could get working. Is there an easier way that I am completely missing?
/* creating the table */
let propertyTable = document.createElement('table');
propertyTable.classList.add('expand','ignore');
let selected = ["", "", "", "", "", ""];
switch (this.type) {
case "number":
selected[0] = "selected";
break;
case "dropDown":
selected[1] = "selected";
break;
case "autoSet":
selected[2] = "selected";
break;
case "plotly":
selected[3] = "selected";
break;
case "gradeGroup":
selected[4] = "selected";
break;
case "generate":
selected[5] = "selected";
break;
}
/* starting the property table */
propertyTable.innerHTML = `<tr class="ignore">
<th class="ignore">ID</th>
<td class="ignore"><input class="tile ignore" value="${this.id}"></td>
</tr>
<tr class="ignore">
<th class="ignore">Type</th>
<td class="ignore">
<select class="tile ignore">
<option value="number" ${selected[0]} class="ignore">number</option>
<option value="dropDown" ${selected[1]} class="ignore">dropDown</option>
<option value="autoSet" ${selected[2]} class="ignore">autoSet</option>
<option value="plotly" ${selected[3]} class="ignore">plotly</option>
<option value="gradeGroup" c${selected[4]} lass="ignore">gradeGroup</option>
<option value="generate" ${selected[5]} class="ignore">generate</option>
</select>
</td>
</tr>`;
2
Answers
Instead of the big
switch
statement, use an array of type names.Could you try a simpler function that you call with the relevant type,
something like:
(Note this is pseudocode, adjust as necessary)
Then when you’re creating the select options, call it:
But really, having a function to build each option would be ideal. Something like:
Which you’d use something like: