Main Page
 The gatekeeper of reality is
 quantified imagination.

Stay notified when site changes by adding your email address:

Your Email:

Bookmark and Share
Email Notification
jsFormElements [Go Back]
This page demonstrates how you can interact with elements of a from through javascript using some newer methods to provide you with more flexibility. At the bottom of the page are a collection of functions that could be of use in the more challenging select box element.

Multiple Forms On A Page With The Same Form Element
In the past, the method of accessing a specific form element in a form was to use the old "forms[0], forms[1]" method. Granted, that works until someone decides that one of the forms is no longer needed in the page and removes it (such as "forms[0]"). This causes your javascript to break if it is trying to access "forms[1]" which no longer exists.

Here's a newer method for accessing a form element (although it is browser-specific) in a form without being limited by the old method mentioned previously. In this case, we are "unchecking" a checkbox in the second form:

<script language="javascript" type="text/javascript">
<!--
var formID = "frm2"; /* The ID of the Form to target, not the name given to the Form. */
var elementName = "cbox"; /* The name of the Form Element in the Form, not the ID given to the Form Element. */
if (navigator.userAgent.toLowerCase().indexOf("msie") != -1) { /*IE*/
if (document.getElementById(formID)(elementName)) { document.getElementById(formID)(elementName).checked = false; }
}
else { /*Other*/
if (document.getElementById(formID)[elementName]) { document.getElementById(formID)[elementName].checked = false; }
}
//-->
</script>
<form id="frm1">
<input type="checkbox" name="cbox" /> Checkbox option
</form>
<form id="frm2">
<input type="checkbox" name="cbox" /> Checkbox option
</form>


Capturing the value of a group of radio buttons with the same name (not the same ID)
With some forms you may have a series of radio buttons that a visitor may select from which represents one type of choice. Capturing the value (a different value defined in each radio button) of what radio button was selected can be a tedious task. The function below will return the value of the selected radio button:

<input type="radio" id="1" name="choice" value="A" />
<input type="radio" id="2" name="choice" value="B" />
<script language="javascript" type="text/javascript">
<!--
function grabRadioSelValue(targetName) {
/* Pass in "choice" when calling this function */
    var targetVal = "";
    var radioBtnSet = document.getElementsByName(targetName);
    for (x = 0; x < radioBtnSet.length; x++) { if (radioBtnSet[x].checked) { targetVal = document.getElementById(radioBtnSet[x].id).value; } }
    return (targetVal);
}
//-->
</script>


Another way to essentially do the same thing as the function specified above is the following function:
function radioGroupValueDiscovery(targetName) {
    /* Rummage through radio button collection to find what value is selected */
    var iValue = 0;
    radioBtnSet = new Array();
    radioBtnSet = document.getElementsByName(targetName);
    for (z = 0; z < radioBtnSet.length; z++) {
        if (document.getElementsByName(targetName)[z].checked == true) { iValue = document.getElementsByName(targetName)[z].value; }
    }
    return (iValue);
}


Capturing The Option Index And Value Of A Select Box (aka drop-down menu)
When someone clicks on an item within a select box, you can capture both the index and text of that selection using "onChange" as shown below. In this case, a simple alert is done to show the data:

<select id="choices" name="choices" onChange="javascript:alert('Option value = ' + this.options[this.selectedIndex].value + '\nOption text = ' + this.options[this.selectedIndex].text);">
<option value="123"> Choice #1 </option>
<option value="456"> Choice #2 </option>
</select> Choose One


Adding An Option To A Select Box Dynamically
With javascript, it is simple to add an option to an already-rendered select box. Here's how to do it:

<script language="javascript" type="text/javascript">
<!--
var selBoxID = "choices";
var selChild = document.createElement("option");
selChild.text = "Choice #2";
selChild.value = "456";
try { document.getElementById(selBoxID).add(selChild, null); }
catch(onerror) { document.getElementById(selBoxID).add(selChild); }
//-->
</script>
<select id="choices" name="choices">
<option value="123"> Choice #1 </option>
</select> Choose One


Removing An Option From A Select Box Dynamically
With javascript, it is simple to remove an option from an already-rendered select box. Here's how to do it:

<script language="javascript" type="text/javascript">
<!--
var selBoxID = "choices";
var optValueRemove = 123;
for (x = document.getElementById(selBoxID).length - 1; x >= 0; x--) {
if (document.getElementById(selBoxID).options[x].value == optValueRemove) { document.getElementById(selBoxID).remove(x); }
}
//-->
</script>
<select id="choices" name="choices">
<option value="123"> Choice #1 </option>
<option value="456"> Choice #2 </option>
</select> Choose One


Removing All Options From A Select Box Dynamically
You can also remove all of the options of a select box. Here's how to do it:

<script language="javascript" type="text/javascript">
<!--
var selBoxID = "choices";
for (x = document.getElementById(selBoxID).options.length - 1; x >= 0; x--) {
document.getElementById(selBoxID).remove(x);
}
//-->
</script>
<select id="choices" name="choices">
<option value="123"> Choice #1 </option>
<option value="456"> Choice #2 </option>
</select> Choose One


Compile Select Box Values Dynamically
With some more elaborate front-end (client-side) requirements, you may need to compile the option values that are contained within a select box. Here's how to do it:

<script language="javascript" type="text/javascript">
<!--
var fullList = "";
var selBoxID = "choices";
for (x = 0; x <= document.getElementById(selBoxID).length - 1; x++) {
if (document.getElementById(selBoxID).options[x].text.length > 0) {
if (fullList.length == 0) { fullList = document.getElementById(selBoxID).options[x].value; }
else { fullList = fullList + "," + document.getElementById(selBoxID).options[x].value; }
}
}
alert(fullList);
//-->
</script>
<select id="choices" name="choices">
<option value="123"> Choice #1 </option>
<option value="456"> Choice #2 </option>
</select> Choose One


Get The Option Value Of Select Box
You can grab the option value of a select box without needing to get the value after the select box option is selected. Here's how to do it:

<script language="javascript" type="text/javascript">
<!--
var optValue = document.getElementById("choices").options[document.getElementById("choices").selectedIndex].value;
alert(optValue);
//-->
</script>
<select id="choices" name="choices">
<option value="123"> Choice #1 </option>
<option value="456"> Choice #2 </option>
</select> Choose One


Clear Out Cached Selections
Most browsers will cache one or more selected options in a select box which can complicate trying to determine what the current selection may be. Here's how to clear out any cached/previously selected selections:

<script language="javascript" type="text/javascript">
<!--
for (x = 0; x < document.getElementById("choices").length; x++) {
document.getElementById("choices").options[x].selectedIndex = false;
document.getElementById("choices").options[x].selected = false;
}
//-->
</script>
<select id="choices" name="choices">
<option value="123" selected> Choice #1 </option>
<option value="456" selected> Choice #2 </option>
</select> Choose One


Select A Select Box Option Based On Option Value
There are times when you need to select an option of a select box with javascript. Here's how to do it:

<script language="javascript" type="text/javascript">
<!--
var optValueMatch = 456;
for (x = 0; x < document.getElementById("choices").length; x++) {
if (document.getElementById("choices").options[x].value.toString() == optValueMatch.toString()) {
document.getElementById("choices").options[x].selected = true;
}
}
//-->
</script>
<select id="choices" name="choices">
<option value="123"> Choice #1 </option>
<option value="456"> Choice #2 </option>
</select> Choose One


Functions to Work with the Select Box Element
There are a lot of things that you can do with a select box which can make it a challenge to work with. The functions below assist with select box actions.

<script language="javascript" type="text/javascript">
		function selSet(target, optvalue) {
			/* Select select box option */
			for (x = 0; x < document.getElementById(target).length; x++) {
				if (document.getElementById(target).options[x].value == optvalue) {
					document.getElementById(target).options[x].selected = true;
				}
			}
		}
		function selClear(target) {
			/* Clear select box selection */
			for (x = 0; x < document.getElementById(target).length; x++) {
				document.getElementById(target).options[x].selectedIndex = false;
				document.getElementById(target).options[x].selected = false;
			}
		}
		function selMake(target, optValue, optText) {
			/* Create select box option */
			var selBoxID = target;
			var selChild = document.createElement("option");
			selChild.text = optText;
			selChild.value = optValue;
			try { document.getElementById(selBoxID).add(selChild, null); }
			catch(onerror) { document.getElementById(selBoxID).add(selChild); }
		}
		function selSelected(target) {
			/* Detect if a select box option has been selected */
			var result = 0;
			for (x = 0; x < document.getElementById(target).options.length; x++) {
				if (eval(document.getElementById(target).options[x].selected)) { result = 1; }
				if (eval(document.getElementById(target).options[x].selectedIndex)) { result = 1; }
			}
			return result;
		}
		function selRemove(target) {
			/* Remove select box options */
			if (document.getElementById(target).options.length > 0) {
				for (x = document.getElementById(target).options.length - 1; x >= 0; x--) {
					document.getElementById(target).remove(x);
				}
			}
		}
		function selRemoveSingle(target, optvalue) {
			/* Remove single select box option */
			var tmp_index = -1;
			for (x = 0; x < document.getElementById(target).length; x++) {
				if (document.getElementById(target).options[x].value == optvalue) {
					tmp_index = x;
				}
			}
			if (tmp_index > -1) {
				document.getElementById(target).options[tmp_index].remove();
			}
		}
		function selFind(target, optvalue) {
			/* Detect if select box option exists */
			var result = 0;
			for (x = 0; x < document.getElementById(target).length; x++) {
				if (document.getElementById(target).options[x].value == optvalue) {
					result = 1;
				}
			}
			return result;
		}
		function selGetOptValues(target) {
			/* Return comma-separated value of the select options present in the select box */
			var tmp_optvalues = "";
			for (x = 0; x < document.getElementById(target).length; x++) {
				if (x == 0) { tmp_optvalues = document.getElementById(target).options[x].value; }
				else { tmp_optvalues = tmp_optvalues + "," + document.getElementById(target).options[x].value; }
			}
			return tmp_optvalues;
		}
</script>


Interpreting Data From A Database
There are times when you need to interpret 'nulls' coming out of a database with javascript before you work with the data. Here's a javascript function that translates NULL based on the type of data expected:

<script language="javascript" type="text/javascript">
<!--
function translateNullData(data, type) {
    if (data == null) {
        if (type.toLowerCase() == "string") { data = ""; }
        else if (type.toLowerCase() == "boolean") { data = false; }
        else if (type.toLowerCase() == "number") { data = 0; }
    }
    return(data);
}
/* Called such as... */
databaseValue = null;
myMobileNumber = translateNullData(databaseValue, "string");
alert(myMobileNumber); /* myMobileNumber will be an empty string */
//-->
</script>
About Joe