Thursday, October 05, 2006

Add/remove options to/from a select list

In my past two posts I've show how to move options between select lists and reorder options in a list. Now, to round out my little series on selection list manipulation with JavaScript, I'll give simple functions to add a value or remove a value from a list.


// addSelectOption
//
// Add the single select option to the selection list with the id specified
//
function addSelectOption(selectId, value, display) {
if (display == null) {
display = value;
}
var anOption = document.createElement('option');
anOption.value = value;
anOption.innerHTML = display;
document.getElementById(selectId).appendChild(anOption);
return anOption;
}

// removeSelectOption
//
// Remove the option with the specified value from the list of options
// in the selection list with the id specified
//
function removeSelectOption(selectId, value) {
var select = document.getElementById(selectId);
var kids = select.childNodes;
var numkids = kids.length;
for (var i = 0; i < numkids; i++) {
if (kids[i].value == value) {
select.removeChild(kids[i]);
break;
}
}
}

1 comment:

D X said...

Thanks, it's simple and works fine!