views:

6446

answers:

4

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>
+3  A: 

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

Hope that helps!

Zachary Yates
+20  A: 

Remove an option :

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

Add an option

$("#selectBox").append('<option value="option5">option5</option>');

The problem here is not how to remove or how to add but I think you should spend more time working with jquery and take time to learn it. When you will have a better understanding of selectors, it will help you a lot.

dan
+1  A: 

I find the jquery select box manipulation plugin useful for things type of thing.

You can easily remove an item by index, value, or regex.

removeOption(index/value/regex/array[, selectedOnly])

Remove an option by
- index: $("#myselect2").removeOption(0);
- value: $("#myselect").removeOption("Value");
- regular expression: $("#myselect").removeOption(/^val/i);
- array $("#myselect").removeOption(["myselect_1", "myselect_2"]);

To remove all options, you can do $("#myselect").removeOption(/./);

Zoredache
A: 

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.

perfectDay