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