
Originally Posted by
Torin Mai
However, unless I've not heard of it, there's no insert function in Javascript for arrays and that's what I need is to be able to insert the option anywhere.
The splice method is the only built-in method capable of inserting an array element at any point. However, if you wanted to use the Option constructor for it's compatibility advantage, you'd also need to provide the splice method for some older browsers which failed to implement it (I have code for that, though).
Hmm. The more XML approach sounds interesting (if awkward). Any chance you could give me an example of what you mean?
How about:
Code:
/* Creates a DOMOptionElement with the given text, value, and selection status.
* If creation fails, the return value is null. The selection status defaults to
* false.
*/
function createOptionElement(text, value, selected) {
var element, textNode;
if (document.createElement && (element = document.createElement('option'))
&& element.appendChild && document.createTextNode
&& (textNode = document.createTextNode(text))) {
element.appendChild(textNode);
element.value = value;
element.selected = Boolean(selected);
return element;
}
return null;
}
/* Inserts an option element into select element at the given position. The position
* can either be expressed as an number in the range [-1,length] where length
* is the number of option elements already in the list, or as a reference to an element
* in the list. Values of -1, length, and null append the item. If given a reference,
* the new option element is inserted before the referenced element. If the position is
* omitted, the option will be appended.
* Upon return, boolean true indicates success, with false signifying failure.
*/
function insertOption(optionElement, selectElement, position) {
if (typeof position == 'number')
if (position == -1) position = null;
else position = selectElement.options[position];
else if (typeof position == 'undefined') position = null;
if (selectElement.insertBefore) {
selectElement.insertBefore(optionElement, position);
return true;
}
return false;
}
I just wrote that quickly, so there's a chance it will break, but I shouldn't think so. Just be sure to test any application of it. 
Mike
Bookmarks