In a dropdown list, I would like to format text from my list ?
In my example below for instance, I’d like to improve the presentation of
"Variable 1 is built with … (long text)"
with bold, line breaks, bullets….
function getOption() {
selectElement = document.querySelector('#select1');
let selectedOption = '';
output = selectElement.value;
switch (output) {
case "var1":
selectedOption = "Variable 1 is built with ... (long text)";
break;
case "var2":
selectedOption = "Variable 2 is important because... (long text)";
break;
default:
selectedOption = "default selected";
}
document.querySelector('.output').textContent = selectedOption;
}
<p>
<select id="select1">
<option value="var1">Variable 1</option>
<option value="var2">Variable 2</option>
<option value="var3">Variable 3</option>
</select>
</p>
<button onclick="getOption()"> Check option </button>
<p> The value of the option selected is:
<span class="output"></span>
</p>
>Solution :
You can use innerHTML and style string directly like:
function getOption() {
selectElement = document.querySelector('#select1');
let selectedOption = '';
output = selectElement.value;
switch (output) {
case "var1":
selectedOption = "<br /><b>Variable 1</b> is built with<br />...<br />(long text)";
break;
case "var2":
selectedOption = "<br /><b>Variable 2</b> is important because... (long text)";
break;
default:
selectedOption = "<br /><b>default</b> selected";
}
document.querySelector('.output').innerHTML = selectedOption;
}
<p>
<select id="select1">
<option value="var1">Variable 1</option>
<option value="var2">Variable 2</option>
<option value="var3">Variable 3</option>
</select>
</p>
<button onclick="getOption()"> Check option </button>
<p> The value of the option selected is:
<span class="output"></span>
</p>
Reference: