settingsAccountsettings
Menusettings

Q: Selectable Towns (task with DOM and jQuery)

+1 vote

Create an HTML page listing towns, a town should be selectable. Clicking on a town should select/deselect it, a selected town should have the data-selected attribute added to it and its background color should be changed to #DDD. Also create a button [Show Towns] that prints the text "Selected towns: " followed by all selected towns joined with a ", ".

HTML and JavaScript Code - You are given the following HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Selectable Towns</title>
    <style>
        li {
            display: inline-block;
            cursor: pointer;
            padding: 10px;
        }
        ul { padding:0; }
    </style>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script src="select-towns.js"></script>
</head>
<body>
<h2>Towns</h2>
<ul id="items">
    <li>Sofia</li>
    <li>Varna</li>
    <li>Plovdiv</li>
    <li>Bourgas</li>
    <li>Rousse</li>
</ul>
<button id="showTownsButton">Show Towns</button>
<div id="selectedTowns"></div>
<script>$(attachEvents())</script>
</body>
</html>

Example:

selectable towns jquery

asked in JavaScript category by user matthew44

1 Answer

+1 vote

HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Selectable Towns</title>
    <style>
        li {
            display: inline-block;
            cursor: pointer;
            padding: 10px;
        }

        ul {
            padding: 0;
        }
    </style>
    <!--<script src="https://code.jquery.com/jquery-3.2.1.js"></script>-->
    <script src="src/jquery-3.2.1.min.js"></script>
    <script src="select-towns.js"></script>
</head>
<body>
<h2>Towns</h2>
<ul id="items">
    <li>Sofia</li>
    <li>Varna</li>
    <li>Plovdiv</li>
    <li>Bourgas</li>
    <li>Rousse</li>
</ul>
<button id="showTownsButton">Show Towns</button>
<div id="selectedTowns"></div>
<script>$(attachEvents())</script>

</body>
</html>

JavaScript file with the jQuery:

function attachEvents() {
    $("#showTownsButton").on("click", show);
    $("#items li").on("click", select);

    function select() {
        let li = $(this);
        if (li.attr("data-selected")) {
            li.removeAttr("data-selected");
            li.css("background", "");
        } else {
            li.attr("data-selected", "true");
            li.css("background", "#ddd")
        }
    }

    function show() {
        let selLi = $("#items li[data-selected=true]");
        let towns = selLi.toArray()
            .map(li=>li.textContent)
            .join(", ");
        $("#selectedTowns").text("Selected towns: " + towns);
    }
}

 

answered by user mitko
...