Estoy programando por primera vez. Quiero escribir un código que mueva varias selecciones de una lista con los botones arriba y abajo en JavaScript. Sin embargo, pude escribir algo que se mueve hacia arriba y hacia abajo, pero no funciona bien si me muevo varias veces. Dígame cómo mover varios elementos seleccionados hacia arriba y hacia abajo.
Si selecciona 3 y 5 y presiona el botón arriba, desea hacer lo siguiente.
<option value = "1"> 1 </ option> <option value = "2"> 2 </ option> <option value = "3"> 3 </ option> <option value = "4"> 4 </ option> <option value = "5"> 5 </ option> <option value = "6"> 6 </ option> ↓ <option value = "1"> 1 </ option> <option value = "3"> 3 </ option> <option value = "2"> 2 </ option> <option value = "5"> 5 </ option> <option value = "4"> 4 </ option> <option value = "6"> 6 </ option> <table> <tr> <td> <select id="item-list" size="8" multiple="multiple"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </td> <td> <input type="button" value="↑" onclick="move('up');"> <br/> <input type="button" value="↓" onclick="move('down');"> </td> </tr> </table> function move(act) { var s = document.getElementById("item-list"); if (s.selectedIndex == -1) return; var opt = s.options[s.selectedIndex]; if (act == 'up') { if (s.options[s.selectedIndex - 1]) { s.insertBefore(opt, s.options[s.selectedIndex - 1]); } } if (act == 'down') { if (s.options[s.selectedIndex + 1]) { s.insertBefore(opt, s.options[s.selectedIndex + 1].nextSibling); } } }Su código tenía varios errores pequeños. lo arreglé
function move(act) { var s = document.getElementById("item-list"); if(s.selectedIndex == -1) return; var opt = s.options[s.selectedIndex]; var opts = s.options; for (let i = 0; i < opts.length; i++) { if (opts[i].selected){ console.log(opts[i].value); if (act == 'up') { if (s.options[s.selectedIndex-1]) { s.insertBefore(opt, s.options[s.selectedIndex-1]); } } if (act == 'down') { if (s.options[s.selectedIndex+1]) { s.insertBefore(opt, s.options[s.selectedIndex+1].nextSibling); } } } } } <table> <tr> <td> <select id="item-list" size="8" multiple="multiple"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </td> <td> <input type="button" value="↑" onclick="move('up');"> <br/> <input type="button" value="↓" onclick="move('down');"> </td> </tr> </table>