Wednesday, June 24, 2009

Loop through form fields in Javascript

The following code will loop through all form fields and look for ones named "chkStores" and checks or unchecks them (assuming they are check boxes). There is a hidden form field named "StoreCheck" that tells whether the current state is checked or unchecked. The action becomes the reverse of the "StoreCheck" value


function check_all()
{
var chkStatus = eval("document.forms[0].StoreCheck.value");
var form = document.forms[0];
var theName = "chkStores";
var len = form.elements.length;
for (var i = 0; i < len; i++)
{
var e = form.elements[i];
if (e.name == theName)
{
if (chkStatus == "unchecked")
{
e.checked = true;
eval("document.forms[0].StoreCheck.value = 'checked'");
}
else
{
e.checked = false;
eval("document.forms[0].StoreCheck.value = 'unchecked'");
}
}
}
}


This code displays the checkboxes and a clickable span to check all.


<code>
<span style="text-decoration: underline;" onmouseover="this.style.cursor='hand';return overlib('Click Here To Check/Uncheck All Stores');" onmouseout="return nd();" onclick="javascript:check_all()">Stores
</span>
<input type="Hidden" name="StoreCheck" value="unchecked">

<cfoutput query="qryGetActiveStores">
<input type="checkbox" name="chkStores" value="#trim(qryGetActiveStores.Store)#">#qryGetActiveStores.Store#
</cfoutput>
</code>

No comments: