Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Example</title>
<style type="text/css">
body
{
font-family: verdana,arial,sans-serif;
font-size: 12px;
}
form span.title
{
font-weight: bold;
margin: 0 4px 0 0;
}
</style>
<script type="text/javascript">
// <![CDATA[
/*Author: itsallkizza*/
function add_option_to(select,option_name,option_value)
{
if (document.createElement)
{
var new_option = document.createElement("option");
new_option.value = option_value;
new_option.innerHTML = option_name;
if (select.appendChild)
{
select.appendChild(new_option);
return new_option;
}
}
return null;
}
function remove_option_by_index(select,index)
{
if (select.removeChild && select.options && select.options.length > index)
{
select.removeChild(select.options[index]);
return true;
}
return false;
}
function addNewOption(form_element)
{
var new_name = form_element.new_option_name.value || false;
var new_value = form_element.new_option_value.value || "";
if (!new_name) return false;
add_option_to(document.getElementById(form_element.select_id.value),new_name,new_value);
return false;
}
function removeOption(form_element)
{
var index = form_element.option_index.value || false;
if (!index || isNaN(index)) return false;
remove_option_by_index(document.getElementById(form_element.select_id.value),index);
return false;
}
// ]]>
</script>
</head>
<body>
<form onsubmit="return addNewOption(this)">
<input type="hidden" name="select_id" value="my_select" />
<span class="title">New Option Name:</span><input type="text" name="new_option_name" />
<span class="title">New Option Value:</span><input type="text" name="new_option_value" />
<input type="submit" value="Add New Option" />
</form>
<form onsubmit="return removeOption(this)">
<input type="hidden" name="select_id" value="my_select" />
<span class="title">Remove Option Index:</span><input type="text" name="option_index" />
<input type="submit" value="Remove Option" />
</form>
<select id="my_select">
<option value="apples">Apples</option>
<option value="bananas">Bananas</option>
<option value="oranges">Oranges</option>
</select>
</body>
</html>