Estoy creando un menú desplegable y en ese menú desplegable tengo una opción llamada otros, cuando se seleccionan otros, aparece un nuevo cuadro de texto y el usuario puede ingresar cualquier valor. Ahora quiero que este valor ingresado se agregue a mis opciones desplegables. Hasta ahora, pude implementar la primera mitad y ahora no puedo agregar el nuevo valor a mi menú desplegable.
function CheckColors(val){ var element=document.getElementById('popup'); if (val=='others') { element.style.display='block';} else { element.style.display='none'; } } <select name="color" onchange='CheckColors(this.value);'> <option>pick a color</option> <option>10%</option> <option>20%</option> <option>30%</option> <option>40%</option> <option value="others" >others </option> <input type="button" name="button" value="Add"/> </select> <input type="text" id="popup" style='display:none;'/>Debería obtener el valor que se agregó al cuadro de texto y crear un nuevo elemento para almacenar dentro de la select .
Aquí, estoy usando createElement para crear una nueva option cuando el usuario hace clic en add . Luego, estoy configurando su contenido usando innerText a lo que se agregó a la entrada.
Hice esto al hacer clic en el botón add , pero podría usarse en otro lugar. También agregué una marca para que no agreguemos un valor vacío como opción.
const CheckColors = (val) => { const element = document.getElementById('popup') if (val === 'others') { element.style.display = 'block' } else { element.style.display = 'none' } } const addBtn = document.querySelector('input[type="button"]') // Add a listener for when the add button is clicked addBtn.addEventListener('click', () => { // get our dropdown and text box const dropdown = document.getElementsByTagName('select')[0] const element = document.getElementById('popup') // Only add the value to the dropdown if it's not blank if (element.value.length !== 0) { // create the new option to add to our select const option = document.createElement('option') // Add the text that was in the text box option.innerText = element.value // Optionally give the option a value option.value = 'something' // Let's select this option too option.selected = true // Add the option to the select dropdown.appendChild(option) } }) <select name="color" onchange='CheckColors(this.value);'> <option>pick a color</option> <option>10%</option> <option>20%</option> <option>30%</option> <option>40%</option> <option value="others" >others </option> <input type="button" name="button" value="Add"/> </select> <input type="text" id="popup" style='display:none;'/>