• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

72
Views
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

almost 3 years ago · Santiago Trujillo
2 answers
Answer question

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>

almost 3 years ago · Santiago Trujillo Report

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.

almost 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error