Wim Roffal wrote:
I want to insert an option into a select.
I know you can do something like:
- Myselect.options[3] = new Option('Hello 3');
but that doesn't do what I want because it overwrites an existing option.
I have the existing options ordered on alphabet and the new option should
fit in on the right place. Of course I can move all the options that come
after the new one, but I wondered if there is a smarter way to do this.
It depends on what browsers you want to support. Netscape 4, 6, 7,
Mozilla, IE 4, 5, 6, will allow you to set
select.options.length = select.options.length + 1;
then move some options and set
select.options[index] = new Option(...)
With newer browsers supporting the W3C DOM you should be able to simply
insert a new <option> element node into the select e.g. using insertBefore:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>inserting an option into a select with DOM Core methods</title>
<script type="text/javascript">
function insertOption (select) {
var newOption, optionToInsertBefore;
if (document.createElement && (newOption =
document.createElement('option'))) {
newOption.appendChild(document.createTextNode('opt ion created ' +
new Date()));
if (select.selectedIndex > -1) {
optionToInsertBefore = select.options[select.selectedIndex];
}
else {
optionToInsertBefore = null;
}
select.insertBefore(newOption, optionToInsertBefore);
}
}
</script>
</head>
<body>
<form action=""
onsubmit="return false;">
<p>
<select id="aSelect" size="5">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<input type="button" value="insert new option before selected option"
onclick="insertOption(this.form.aSelect);">
</p>
</form>
</body>
</html>
Tested with Netscape 7, IE6, and Opera 7, it should work with IE5 and
Netscape 6 as well.
If you look at the DOM HTML module at
http://www.w3.org/TR/DOM-Level-2-HTM...ml#ID-94282980
then you will see that HTMLSelectElement objects should also have an add
method. That method should work with Netscape 6/7 and Opera 7 while IE5+
also has that method but with different arguments so you are better off
using insertBefore in my view.
--
Martin Honnen
http://JavaScript.FAQTs.com/