PDA

View Full Version : "Other" options for <select /> menus


]|V|[agnus
03-05-2005, 03:48 AM
function disenableOthers(container,triggerPhrase) {

/*

This function serves the following purpose:

To allow users the option of a predefined
(perhaps generated dynamically) set of <option />s
via a <select /> element the ability to select
"Other" and fill in the blank. The blank being
a supplementary <input type="text" />. "Other"
being a trigger phrase of your choice.

This function relies on the following convention:

Each <select />'s supplementary <input /> should
be ID'd as such:

selectID + triggerPhrase = otherInputID

*/

// first, check for the existence of a container element.
// you can ID the container element whatever you want,
// so it's easier to use on multiple forms in one site.
// just pass the container element's ID to the function.
var container = document.getElementById(container);
if (container) {

// all "Other" <input />s are disabled by default.
var inputs = container.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var inputID = inputs[i].getAttribute("id");
var chunk = inputID.substring((inputID.length - triggerPhrase.length),inputID.length)
if (chunk == triggerPhrase) {inputs[i].disabled = true;}
}

var selects = container.getElementsByTagName("select");
for (var s = 0; s < selects.length; s++) {

selects[s].onchange = function() {

// when the "Other" <option /> is selected,
// the <input /> is enabled/focused.
// it is disabled/blurred when the "Other" <option /> is deselected.

var theOther = document.getElementById(this.getAttribute("id") + triggerPhrase);

if (this.options[this.selectedIndex].value == triggerPhrase) {
theOther.disabled = false; theOther.focus();
} else {
theOther.disabled = true;
}

};

}

}
}

// run this function on load.
// wee!