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()">>></button> <button type="button" onclick="move2()"><<</button> <select id="select2"></select>Puedes hacerlo así:
getElementById() y guárdelas en las variables select_1 y select_2 .selectedIndex de la selección con -1 . Será igual a -1 solo si el usuario no seleccionó nada.selectedIndex es igual a -1 , no haga nada porque no hay nada que transferir a la segunda selección.selectedIndex es diferente de -1 , significa que el usuario seleccionó algo y la opción con ese índice debe transferirse.document.createElement('option') y copie los valores de la opción seleccionada en la nueva opción.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()">>></button> <button type="button" onclick="move2()"><<</button> <select id="select2"></select>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">>></button> <button name='B' type="button"><<</button> <select id="B"></select>