Removing an item from a select box
How do I remove items from, or add items to, a select box? I'm running jQuery, should that make the task easier. Below is an example select box.
<select name="selectBox" id="selectBox">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
Solution 1:
Remove an option:
$("#selectBox option[value='option1']").remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="selectBox" id="selectBox">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
Add an option:
$("#selectBox").append('<option value="option5">option5</option>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="selectBox" id="selectBox">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
Solution 2:
You can delete the selected item with this:
$("#selectBox option:selected").remove();
This is useful if you have a list and not a dropdown.
Solution 3:
window.onload = function ()
{
var select = document.getElementById('selectBox');
var delButton = document.getElementById('delete');
function remove()
{
value = select.selectedIndex;
select.removeChild(select[value]);
}
delButton.onclick = remove;
}
To add the item I would create second select box and:
var select2 = document.getElementById('selectBox2');
var addSelect = document.getElementById('addSelect');
function add()
{
value1 = select2.selectedIndex;
select.appendChild(select2[value1]);
}
addSelect.onclick = add;
Not jQuery though.