Removing an item from a select box

2019-01-03 00:49发布

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>

15条回答
Fickle 薄情
2楼-- · 2019-01-03 01:18

You can delete the selected item with this:

$("#selectBox option:selected").remove();

This is useful if you have a list and not a dropdown.

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-03 01:25
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.

查看更多
Animai°情兽
4楼-- · 2019-01-03 01:25

I had to remove the first option from a select, with no ID, only a class, so I used this code successfully:

$('select.validation').find('option:first').remove();
查看更多
干净又极端
5楼-- · 2019-01-03 01:27

To Remove an Item

$("select#mySelect option[value='option1']").remove(); 

To Add an item

$("#mySelect").append('<option value="option1">Option</option>');

To Check for an option

$('#yourSelect option[value=yourValue]').length > 0;

To remove a selected option

$('#mySelect :selected').remove(); 
查看更多
男人必须洒脱
6楼-- · 2019-01-03 01:29
家丑人穷心不美
7楼-- · 2019-01-03 01:29

Just to augment this for anyone looking, you are also able to just:

$("#selectBox option[value='option1']").hide();

and

$("#selectBox option[value='option1']").show();
查看更多
登录 后发表回答