settingsAccountsettings
Menusettings

Q: Add / Remove Towns (Simple DOM Interaction)

+2 votes

You are given the following HTML code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Add / Remove Towns</title>
    <style>select, input { width: 100px }</style>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>

<body onload="attachEvents()">

<div>Towns</div>
<select id="towns" size="4">
    <option>Sofia</option>
    <option>Varna</option>
    <option>Pleven</option>
</select>

<button id="btnDelete">Delete</button>

<div>
    <input type="text" id="newItem" />
    <button id="btnAdd">Add</button>
</div>

<script>
    function attachEvents() {
        // TODO: …
    }
</script>
</body>
</html>

Your Task:

Write the missing JavaScript code to make the [Add] and [Delete] buttons work as expected.

  • The [Add] button should append the text from the text box as a new item at the end of the list box and clear the input text box after that. If the textbox is empty, it should do nothing.
  • The [Delete] button should delete selected item from the list. If no item is selected, it should do nothing.
    • When an item is selected it has the property selected.

Examples:

add remove town 1

add remove town 2

asked in JavaScript category by user mitko

1 Answer

+2 votes

Here is the HTML file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Add / Remove Towns</title>
    <style>select, input {
        width: 100px
    }</style>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>

<body onload="attachEvents()">

<div>Towns</div>
<select id="towns" size="4">
    <option>Sofia</option>
    <option>Varna</option>
    <option>Pleven</option>
</select>
<button id="btnDelete">Delete</button>

<div>
    <input type="text" id="newItem"/>
    <button id="btnAdd">Add</button>
</div>

<script>
    function attachEvents() {
        $("#btnDelete").on("click", function () {
            $("#towns :selected").remove();//or:
        });

        $("#btnAdd").click(function () {
            let town = $("#newItem").val();
            if (town !== "") {
                let option = $("<option>").text(town);
                $("#towns").append(option);
                $("#newItem").val("");
            }
        });
    }
</script>
</body>
</html>

And the JavaScript function:

function attachEvents() {
    $("#btnDelete").on("click", function () {
        $("#towns :selected").remove();
    });

    $("#btnAdd").click(function () {
        let town = $("#newItem").val();
        if (town !== "") {
            let option = $("<option>").text(town);
            $("#towns").append(option);
            $("#newItem").val("");
        }
    });
}

BTW, for the selected you can aslo use: https://stackoverflow.com/questions/10659097/jquery-get-selected-option-from-dropdown

answered by user paulcabalit
edited by user golearnweb
...