Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
mover la opción de una selección a otra selección con JS

De dos selecciones html, me gustaría mover cuando hago clic en el botón para mover una opción a otra selección con javascript vanila, y cuando se ha movido, se elimina de la selección de donde estaba al principio. También debería funcionar al revés.

 function move1() { var x = document.getElementById("select1"); } function move2() {}
 <select id="select1"> <option value="0">1</option> <option value="0">2</option> <option value="0">3</option> </select> <button type="button" onclick="move1()">&gt;&gt;</button> <button type="button" onclick="move2()">&lt;&lt;</button> <select id="select2"></select>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Puedes hacerlo así:

  • Obtenga ambas selecciones con getElementById() y guárdelas en las variables select_1 y select_2 .
  • Compruebe si existe la opción selectedIndex de la selección con -1 . Será igual a -1 solo si el usuario no seleccionó nada.
  • Si el selectedIndex es igual a -1 , no haga nada porque no hay nada que transferir a la segunda selección.
  • Si el índice selectedIndex es diferente de -1 , significa que el usuario seleccionó algo y la opción con ese índice debe transferirse.
  • Cree una nueva opción para la segunda selección con document.createElement('option') y copie los valores de la opción seleccionada en la nueva opción.
  • Eliminar la opción seleccionada de la selección actual con select.options.remove(select.selectedIndex)

 function move1() { const select_1 = document.getElementById("select1"); const select_2 = document.getElementById("select2"); if(select_1.selectedIndex !== -1) { const selected_option = select_1.options[select_1.selectedIndex]; let new_option = document.createElement('option'); new_option.value = selected_option.value new_option.innerHTML = selected_option.innerHTML; select_2.appendChild(new_option); select_1.options.remove(select_1.selectedIndex) } } function move2(){ const select_1 = document.getElementById("select1"); const select_2 = document.getElementById("select2"); if(select_2.selectedIndex !== -1) { const selected_option = select_2.options[select_2.selectedIndex]; let new_option = document.createElement('option'); new_option.value = selected_option.value new_option.innerHTML = selected_option.innerHTML; select_1.appendChild(new_option); select_2.options.remove(select_2.selectedIndex) } }
 <select id="select1"> <option value="0">1</option> <option value="0">2</option> <option value="0">3</option> </select> <button type="button" onclick="move1()">&gt;&gt;</button> <button type="button" onclick="move2()">&lt;&lt;</button> <select id="select2"></select>

about 4 years ago · Juan Pablo Isaza Report

0

Aquí hay una versión que puede administrar más de 2 conjuntos de pares <select> y <button> . Si hay más de 2 pares, todos los que reciban <select> agregarán la <option> seleccionada. En el HTML, se agrega un atributo data-* a cada <option> :

 <option data-idx="0" value='1'>1</option> <option data-idx='1' value="2">2</option> <option data-idx='2' value="3">3</option>

El valor de data-idx es la posición de índice original de <option> s. En el controlador de eventos switchOPt(e) , el valor data-idx se usará para determinar en qué índice debe colocarse:

 to.add(copy, +copy.dataset.idx);

Todos los detalles se comentan en el ejemplo.

 /* Collect all buttons into a HTMLCollection then convert it into an Array. Same with all select */ const btnArray = [...document.querySelectorAll('button')]; const selArray = [...document.querySelectorAll('select')]; /* Iterate through the array of buttons. Register each button to the click event. The event handler is switchOpt(e) */ btnArray.forEach(btn => btn.addEventListener('click', switchOpt)); // Event handler always passes the Event Object function switchOpt(e) { /* Determine the select that will send it's option by matching it's #id vs this.name (the [name] of the button the user clicked */ const from = document.getElementById(this.name); // if the select doesn't have any options end function if (from.childElementCount < 1) return; /* Determine the select that adds an option by .filter() under the condition that it is NOT >from< */ let to = selArray.filter(sel => sel.id != from.id); // Rereference >to< to be the select with the array to = to[0]; // Determine which option has been selected const opt = from.options[from.selectedIndex]; // Make a copy of the selected option const copy = opt.cloneNode(true); /* Add >copy< to >to< the second parameter is the index of the element that >copy< will be placed before it so it'll always be in order */ to.add(copy, +copy.dataset.idx); // Remove the option from >from< opt.remove(); }
 <!-- Assign each option a data attribute wuth the value of it's index --> <select id="A"> <option data-idx='0' value="1">1</option> <option data-idx='1' value="2">2</option> <option data-idx='2' value="3">3</option> </select> <button name='A' type="button">&gt;&gt;</button> <button name='B' type="button">&lt;&lt;</button> <select id="B"></select>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!