Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

91
Visualizações
Agregar opción al cuadro de selección

Acabo de ver un ejemplo de un cuadro de selección en el que puede agregar una opción escribiendo una opción que no existe en el cuadro de selección y haciendo clic en Enviar,

 function myFunction() { var x = document.getElementById("mySelect"); var option = document.createElement("option"); option.text = "Kiwi"; x.add(option); }

Entonces, mi pregunta es ¿cómo puedo cambiar "kiwi" a cualquier otra palabra que el usuario pueda insertar?


quiero dejar que el usuario inserte la palabra que quiere, "kiwi debe incluirse en mi js", pero ¿qué pasa con el usuario? ¿Cómo puede hacer eso? Ni siquiera sé si este es el método correcto para agregar una opción para seleccionar cuadro, lo siento si mi pregunta no fue clara

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Debe tomar texto de una entrada al hacer clic en un botón y luego asignar ese texto a un nuevo elemento de opción. Finalmente, agréguelo al elemento seleccionado.

Para que esto sea escalable, vamos a crear un div para contener todos nuestros elementos y asignar el detector de eventos a ese elemento. Luego podemos usar la difusión de eventos y la magia de this palabra clave para obtener el texto apropiado y asignarlo al elemento de select apropiado.

 //Find our fancy select elements document.querySelectorAll(".fancy-select").forEach(function(fancySelect){ //Add a click event handler - //NOTE that "this" will refer to the clicked "fancy select element" fancySelect.addEventListener("click", function(event){ //Check the event origingated from the button if(event.target.matches("button")){ //Get the text element in "this" fancy-select element let textElement = this.querySelector(".addOptionText"); //Check there is text if(textElement.value !== ""){ //Create and option element let option = document.createElement("option"); //Givie it the text option.innerHTML = textElement.value; //Append it to the select this.querySelector("select").appendChild(option); //optionally select the new element this.querySelector("select").selectedIndex = this.querySelector("select").options.length - 1; //Finally empty the text box textElement.value = ""; } } }); });
 .fancy-select{display:inline-block;} .fancy-select select {display:block; min-width:200px;}
 <div class="fancy-select"> <input type="text" class="addOptionText"/><button type="button">+</button> <select> <option>Select 1 Option 1</option> <option>Select 1 Option 2</option> <option>Select 1 Option 3</option> </select> </div> <div class="fancy-select"> <input type="text" class="addOptionText"/><button type="button">+</button> <select> <option>Select 2 Option 1</option> <option>Select 2 Option 2</option> <option>Select 2 Option 3</option> </select> </div>

about 4 years ago · Santiago Trujillo Relatório

0

 function myFunction() { var x = document.getElementById("mySelect"); var option = document.createElement("option"); option.text = document.getElementById("text").value; x.add(option); }
 body, button{ font-family: consolas, sans-serif; } h1,h2,h3{ border-bottom: 2px solid black; }
 <h1>Add Options!</h1> <mark>Sorry, but your question was not clear enough and I could not fully understand it. Here is my best shot at answering the question.</mark> <h2> Result </h2> <textarea placeholder = "Type here" id = "text"></textarea> <input type = "submit" onclick = "myFunction()"> <br> <select id = "mySelect"> </select>

Primero, obtenga un área de texto ( <textarea></textarea> ) y haga el id = "texto". Si ya tiene un área de texto o una entrada, puede omitir este paso.

Entonces, puedes poner

 option.text = document.getElementById("text").value; //instead of option.text = "kiwi";

El .value al final es para entradas y áreas de texto y le dice al programa lo que el usuario ha ingresado.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda