0
const ddselect = () => {
  let displayText = selectTag.options.text;
  let list = document.querySelector(".list");
  let listItem = document.createElement("li");
  listItem.innerHTML = displayText;
  console.log(listItem);
};

How do I create an li if the option in select tag is selected? I have 8 options in the select tag. I assume i have to loop through the options

AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21
ivexy
  • 21
  • 3
  • Does this answer your question? [Get selected value in dropdown list using JavaScript](https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript) – FZs Apr 08 '21 at 11:00

1 Answers1

2

Although it's unclear for me whether you want to create a li element only on a certain selected option, or different li elements for every selected option, but one way of doing what I think you're trying to do is...

Add an Event Listener to your <select> that listens to the change event, then inside this listener's callback function do whatever you want based on the selected value / option.

A short example;

var myOl = document.querySelector("#myol");
var select = document.querySelector("#myselect");

select.addEventListener("change", function(event){

  // Create a new Li element
  let newLi = document.createElement("li");
  // Set the Li Element's Text Content to the selected Option's Text Content
  newLi.textContent = event.target.options[event.target.selectedIndex].textContent;

  // Alternatively you could create a switch / if structure based on event.target.value
  /*
  switch( event.target.value )
  {
      case "1":
          // Do stuff in case of the first option
          break;
      case "2":
          // Do stuff in case of the second option
          break;
      // Etc
  }
  */

  // Add the new Li to the OL
  myOl.appendChild( newLi );

});
<select id="myselect">
  <option value="1">First Option!</option>
  <option value="2">Second Option!</option>
  <option value="3">Third Option!</option>
  <option value="4">Fourth Option!</option>
</select>

<ol id="myol"></ol>
Alain Doe
  • 532
  • 3
  • 7