3
20/10/2024 1:28 pm
Topic starter
You are given the following HTML code:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Move Up / Down</title> <style> select { width: 70px } .block { display: inline-block; vertical-align: top } #btnUp { display: block; margin-top: 18px } #btnDown { display: block; margin-top: 10px } </style> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> </head> <body> <div class="block"> <select id="towns" size="5"> <option>Sofia</option> <option>Varna</option> <option>Plovdiv</option> <option>Ruse</option> </select> </div> <div class="block"> <button id="btnUp" onclick="move(-1)">↑</button> <button id="btnDown" onclick="move(+1)">↓</button> </div> <script> function move(direction) { // TODO: … } </script> </body> </html>
Your Task:
Write the missing JavaScript code to make the arrow buttons work as expected.
- The [↑] button move the selected item up in the list. If no item is selected, it should do nothing.
- The [↓] button should move the selected item down in the list. If no item is selected, it should do nothing.
Note: When an item is selected, it has the property selected.
Examples:
1 Answer
2
20/10/2024 1:29 pm
Here is the JavaScript function solution:
function move(direction) { let townToMove = $('#towns option:selected'); if (direction == -1) { townToMove.insertBefore(townToMove.prev()); } if (direction == +1) { townToMove.insertAfter(townToMove.next()); } }