Remove Selected Value in Dropdown List Using JavaScript
20,014
As you've jQuery loaded on the page, use it to bind events and remove element from DOM.
First, bind click event on the button using click
. Use the :selected
pseudo-selector to select the selected option from the dropdown and remove()
to remove it from DOM.
$('button').click(function() {
$('#shipSelec option:selected').remove();
});
$(document).ready(function() {
$('button').click(function() {
$('#shipSelec option:selected').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ShipPlacement">
Ship:
<select name="shipSelec" id="shipSelec">
<option value="aircraftCarrier">Aircraft Carrier</option>
<option value="battleship">Battleship</option>
<option value="cruiser">Cruiser</option>
<option value="destroyer">Destroyer</option>
<option value="destroyer">Destroyer</option>
<option value="submarine">Submarine</option>
<option value="submarine">Submarine</option>
</select>
<button type="button">Remove Selected Ship</button>
</div>
Note that there are several issues in your code
- In fiddle "LOAD TYPE" option should be selected to "No Wrap".
- jQuery is not included. This can be included using the "Frameworks & Extensions" option in the JavaScript tab
- Syntax error in the first statement in the
placeShip()
near.value;);
-
shipList
is local to theready
callback and hence not accessible from outside of it. Not even inplaceShip()
With pure JavaScript
var shipList = document.getElementById('shipSelec');
shipList.options[shipList.selectedIndex].remove();
Author by
Larrimus
Updated on July 12, 2022Comments
-
Larrimus almost 2 years
I have an HTML list that I want to remove elements from as the user chooses. I've tried using this code from this thread but my issue seems to be accessing the element. Here's my HTML:
<div id="ShipPlacement"> Ship: <select name="shipSelec" id="shipSelec"> <option value="aircraftCarrier">Aircraft Carrier</option> <option value="battleship">Battleship</option> <option value="cruiser">Cruiser</option> <option value="destroyer">Destroyer</option> <option value="destroyer">Destroyer</option> <option value="submarine">Submarine</option> <option value="submarine">Submarine</option> </select> <button type="button" onclick="placeShip()">Remove Selected Ship</button>
And here's my JavaScript:
$( document ).ready(function() { var shipList=document.getElementById('shipSelec'); }); function placeShip() { shipList.remove(shipList.options[shipList.selectedIndex].value;); shipList.remove(shipList.options[shipList.selectedIndex]); shipList.remove(shipList.options[selectedIndex]); shiplist.remove([shipList.selectedIndex]) }
I have several instances of the
remove()
method but that none of them work. However, the best way I can convey my error to you is through JSFiddle.