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条回答
Viruses.
2楼-- · 2019-01-03 01:43

I just want to suggest another way to add an option. Instead of setting the value and text as a string one can also do:

var option = $('<option/>')
                  .val('option5')
                  .text('option5');

$('#selectBox').append(option);

This is a less error-prone solution when adding options' values and texts dynamically.

查看更多
Lonely孤独者°
3楼-- · 2019-01-03 01:43

If somebody need delete ALL options inside a select, i did a litle function.

I hope you find it useful

var removeAllOptionsSelect = function(element_class_or_id){
    var element = $(element_class_or_id+" option");
    $.each(element,function(i,v){
        value = v.value;
        $(element_class_or_id+" option[value="+value+"]").remove(); 
    })
}

Only have to run

removeAllOptionsSelect("#contenedor_modelos");
查看更多
虎瘦雄心在
4楼-- · 2019-01-03 01:44

I found two pages that seem helpful, it's written for ASP.Net, but the same stuff should apply:

  1. How to add/remove items from a dropdown list using jQuery
  2. jQuery selector expressions
查看更多
登录 后发表回答