简体   繁体   中英

How do I create an element if the option in select tag is selected

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM