Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to format text create by a dropdown list?

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading