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);
}
}