[dev] VarRenderer and custom events

Matt matt at kynx.org
Sat Mar 6 08:54:33 PST 2004


Sorry to take a bit. Was held hostage on a friend's sailboat. Rough life
:)

> Yes, that sounds like the right way to go. I purposely didn't complete the
> Horde_Form_Action work when I did it; some of it was pretty specific, and I
> didn't have the time to do it generally. Anything that makes it more general,
> portable, and useful would be welcome. :)

Diff for framework/UI/UI/VarRenderer/html.php is attached.

I've added a new function _getActionScripts() which returns a string
'[action]="[script]"', and added this to each of the _renderVarInput_*
functions *except* image/file/matrix/sort/etc, which are all a bit
special.

I've also taken the liberty to output all tags in the functions I
touched with printf to make them more readable. Hope that's OK. I also
started mucking with the monthdayyear functions to try and get it
outputting stuff in unamerican 'd m Y' order, but couldn't figure out
how to test for that.

I haven't had the time to test every last one, but the basics seem to be
working.

> > Incidentally, the stuff I'm adding is for automatically summing elements
> > (el1 = el2 + el3 + ...) and another for making the enabled state of one
> > element dependant on the value of another. Any interest?
> 
> Sure! Send 'em along.

Attached:
framework/Form/Form/Action/conditional_enable.php
framework/Form/Form/Action/sum_fields.php
horde/templates/javascript/form_helpers.js

Time for the pub,

Matt
-------------- next part --------------
--- html.php.orig	2004-03-06 11:28:13.000000000 +0000
+++ html.php	2004-03-06 11:31:13.000000000 +0000
@@ -29,44 +29,48 @@
         if (!empty($linfo['mon_decimal_point'])) {
             $value = str_replace('.', $linfo['mon_decimal_point'], $value);
         }
-        printf('<input type="text" size="5" name="%s" value="%s" />',
+        printf('<input type="text" size="5" name="%s" value="%s"%s />',
                $var->getVarName(),
-               $value);
+               $value,
+               $this->_getActionScripts($form, $var, $index));
     }
 
     function _renderVarInput_int(&$form, &$var, &$vars, $index = null)
     {
-?><input type="text" size="5" name="<?php echo $var->getVarName() ?>" value="<?php echo $var->getValue($vars, $index) ?>" />
-<?php
+        printf('<input type="text" size="5" name="%s" value="%s"%s />',
+               $var->getVarName(),
+               $value = $var->getValue($vars, $index),
+               $this->_getActionScripts($form, $var, $index));
     }
 
     function _renderVarInput_octal(&$form, &$var, &$vars, $index = null)
     {
-?><input type="text" size="5" name="<?php echo $var->getVarName() ?>" value="<?php echo sprintf('0%o', octdec($var->getValue($vars, $index))) ?>" />
-<?php
+        printf('<input type="text" size="5" name="%s" value="%s"%s />',
+               $var->getVarName(),
+               sprintf('0%o', octdec($var->getValue($vars, $index))),
+               $this->_getActionScripts($form, $var, $index));
     }
 
     function _renderVarInput_intlist(&$form, &$var, &$vars, $index = null)
     {
-?><input type="text" name="<?php echo $var->getVarName() ?>" value="<?php echo $var->getValue($vars, $index) ?>" />
-<?php
+        printf('<input type="text" name="%s" value="%s"%s />',
+               $var->getVarName(),
+               $value = $var->getValue($vars, $index),
+               $this->_getActionScripts($form, $var, $index));
     }
 
     function _renderVarInput_text(&$form, &$var, &$vars, $index = null)
     {
         $maxlength = $var->type->getMaxLength();
-        printf('<input type="text" name="%s" size="%s" value="%s" %s%s%s',
+        printf('<input type="text" name="%s" size="%s" value="%s" %s%s%s%s />',
                $var->getVarName(),
                $var->type->getSize(),
                @htmlspecialchars($var->getValue($vars, $index), ENT_QUOTES, NLS::getCharset()),
                $this->_genID($var->getVarName(), $index),
                $var->isDisabled() ? ' disabled="disabled" ' : '',
-               empty($maxlength) ? '' : ' maxlength="' . $maxlength . '"'
+               empty($maxlength) ? '' : ' maxlength="' . $maxlength . '"',
+               $this->_getActionScripts($form, $var, $index)
                );
-        if ($var->hasAction()) {
-            $this->_genActionScript($form, $var->_action, $var->getVarName(), $index);
-        }
-        echo ' />';
     }
 
     function _renderVarInput_weatherdotcom(&$form, &$var, &$vars, $index = null)
@@ -76,14 +80,18 @@
 
     function _renderVarInput_stringlist(&$form, &$var, &$vars, $index = null)
     {
-?><input type="text" size="60" name="<?php echo $var->getVarName() ?>" value="<?php echo $var->getValue($vars, $index) ?>" />
-<?php
+        printf('<input type="text" size="60" name="%s" value="%s"%s />',
+               $var->getVarName(),
+               $value = $var->getValue($vars, $index),
+               $this->_getActionScripts($form, $var, $index));
     }
 
     function _renderVarInput_file(&$form, &$var, &$vars, $index = null)
     {
-?><input type="file" size="30" name="<?php echo $var->getVarName() ?>" value="<?php echo $var->getValue($vars, $index) ?>" />
-<?php
+        printf('<input type="file" size="30" name="%s" value="%s"%s />',
+               $var->getVarName(),
+               $value = $var->getValue($vars, $index),
+               $this->_getActionScripts($form, $var, $index));
     }
 
     /**
@@ -209,16 +217,18 @@
 
         $id = $this->_genID($var->getVarName(), $index, false);
 
-        printf('<textarea id="%s" name="%s" cols="%s" rows="%s">%s</textarea>',
+        printf('<textarea id="%s" name="%s" cols="%s" rows="%s"%s>%s</textarea>',
                $id,
                $var->getVarName(),
                $var->type->getCols(),
                $var->type->getRows(),
+               $this->_getActionScripts($form, $var, $index),
                $var->getValue($vars, $index));
 
         if ($var->type->hasHelper('rte') && $browser->hasFeature('rte')) {
             require_once HORDE_LIBS . 'Horde/Editor.php';
-            $editor = &Horde_Editor::singleton('htmlarea', array('id' => $id));
+            $editor = &Horde_Editor::singleton('htmlarea');
+            $editor->runEditor($id);
         }
 
         if ($var->type->hasHelper() && $browser->hasFeature('javascript')) {
@@ -234,26 +244,41 @@
 
     function _renderVarInput_countedtext(&$form, &$var, &$vars, $index = null)
     {
-?><textarea name="<?php echo $var->getVarName() ?>" cols="<?php echo $var->type->getCols() ?>" rows="<?php echo $var->type->getRows() ?>"><?php echo $var->getValue($vars, $index) ?></textarea>
-<?php
+        printf('<textarea name="%s" cols="%s" rows="%s"%s>%s</textarea>',
+               $var->getVarName(),
+               $var->type->getCols(),
+               $var->type->getRows(),
+               $this->_getActionScripts($form, $var, $index),
+               $var->getValue($vars, $index));
     }
 
     function _renderVarInput_address(&$form, &$var, &$vars, $index = null)
     {
-?><textarea <?php echo $this->_genID($var->getVarName(), $index) ?> name="<?php echo $var->getVarName() ?>" cols="<?php echo $var->type->getCols() ?>" rows="<?php echo $var->type->getRows() ?>"><?php echo $var->getValue($vars, $index) ?></textarea>
-<?php
+        printf('<textarea id="%s" name="%s" cols="%s" rows="%s"%s>%s</textarea>',
+               $this->_genID($var->getVarName(), $index),
+               $var->getVarName(),
+               $var->type->getCols(),
+               $var->type->getRows(),
+               $this->_getActionScripts($form, $var, $index),
+               $var->getValue($vars, $index));
     }
 
     function _renderVarInput_date(&$form, &$var, &$vars, $index = null)
     {
+        printf('<input type="text" name="%s" value="%s"%s />',
+               $var->getVarName(),
+               $value = $var->getValue($vars, $index),
+               $this->_getActionScripts($form, $var, $index));
 ?><input type="text" name="<?php echo $var->getVarName() ?>" value="<?php echo $var->getValue($vars, $index) ?>" />
 <?php
     }
 
     function _renderVarInput_time(&$form, &$var, &$vars, $index = null)
     {
-?><input type="text" size="5" name="<?php echo $var->getVarName() ?>" value="<?php echo $var->getValue($vars, $index) ?>" />
-<?php
+        printf('<input type="text" size="5" name="%s" value="%s"%s />',
+               $var->getVarName(),
+               $value = $var->getValue($vars, $index),
+               $this->_getActionScripts($form, $var, $index));
     }
 
     function _renderVarInput_hourminutesecond(&$form, &$var, &$vars, $index = null)
@@ -265,20 +290,22 @@
         for ($i = 0; $i <= 23; $i++) {
             $hours[sprintf('%02d', $i)] = $i;
         }
-        printf('<select name="%s[hour]" id="%s[hour]">%s</select>',
+        printf('<select name="%s[hour]" id="%s[hour]"%s>%s</select>',
                $varname,
                $varname,
-               $this->_selectOptions($hours, $time['hour']));
+               $this->_selectOptions($hours, $time['hour']),
+               $this->_getActionScripts($form, $var, $index));
 
         /* Output minutes. */
         $minutes = array('' => _("MM"));
         for ($i = 0; $i <= 59; $i++) {
             $minutes[sprintf('%02d', $i)] = $i;
         }
-        printf('<select name="%s[minute]" id="%s[minute]">%s</select>',
+        printf('<select name="%s[minute]" id="%s[minute]"%s>%s</select>',
                $varname,
                $varname,
-               $this->_selectOptions($minutes, $time['minute']));
+               $this->_selectOptions($minutes, $time['minute']),
+               $this->_getActionScripts($form, $var, $index));
 
         /* Return if seconds are not required. */
         if (!$var->type->_show_seconds) {
@@ -290,15 +317,17 @@
         for ($i = 0; $i <= 59; $i++) {
             $seconds[sprintf('%02d', $i)] = $i;
         }
-        printf('<select name="%s[second]" id="%s[second]">%s</select>',
+        printf('<select name="%s[second]" id="%s[second]"%s>%s</select>',
                $varname,
                $varname,
+               $this->_getActionScripts($form, $var, $index),
                $this->_selectOptions($seconds, $time['second']));
     }
 
     function _renderVarInput_monthyear(&$form, &$var, &$vars, $index = null)
     {
-        $months = array('' => _("MM"),
+        $dates = array();
+        $dates['month'] = array('' => _("MM"),
                         1 => _("January"),
                         2 => _("February"),
                         3 => _("March"),
@@ -311,24 +340,30 @@
                         10 => _("October"),
                         11 => _("November"),
                         12 => _("December"));
-        $years = array('' => _("YYYY"));
+        $dates['year'] = array('' => _("YYYY"));
         if ($var->type->_start_year > $var->type->_end_year) {
             for ($i = $var->type->_start_year; $i >= $var->type->_end_year; $i--) {
-                $years[$i] = $i;
+                $dates['year'][$i] = $i;
             }
         } else {
             for ($i = $var->type->_start_year; $i <= $var->type->_end_year; $i++) {
-                $years[$i] = $i;
+                $dates['year'][$i] = $i;
             }
         }
-?><select name="<?php echo $var->type->getMonthVar($var) ?>"><?php echo $this->_selectOptions($months, $vars->get($var->type->getMonthVar($var))) ?></select>
-<select name="<?php echo $var->type->getYearVar($var) ?>"><?php echo $this->_selectOptions($years, $vars->get($var->type->getYearVar($var))) ?></select>
-<?php
+        printf('<select name="%s"%s>%s</select>',
+               $var->type->getMonthVar($var),
+               $this->_getActionScripts($form, $var, $index),
+               $this->_selectOptions($dates['month'], $vars->get($var->type->getMonthVar($var))));
+        printf('<select name="%s"%s>%s</select>',
+               $var->type->getYearVar($var),
+               $this->_getActionScripts($form, $var, $index),
+               $this->_selectOptions($dates['year'], $vars->get($var->type->getYearVar($var))));
     }
 
     function _renderVarInput_monthdayyear(&$form, &$var, &$vars, $index = null)
     {
-        $months = array(''   => _("MM"),
+        $dates = array();
+        $dates['month'] = array(''   => _("MM"),
                         '1'  => _("January"),
                         '2'  => _("February"),
                         '3'  => _("March"),
@@ -341,26 +376,33 @@
                         '10' => _("October"),
                         '11' => _("November"),
                         '12' => _("December"));
-        $days = array('' => _("DD"));
+        $dates['day'] = array('' => _("DD"));
         for ($i = 1; $i <= 31; $i++) {
-            $days[$i] = $i;
+            $dates['day'][$i] = $i;
         }
-        $years = array('' => _("YYYY"));
+        $dates['year'] = array('' => _("YYYY"));
         if ($var->type->_start_year > $var->type->_end_year) {
             for ($i = $var->type->_start_year; $i >= $var->type->_end_year; $i--) {
-                $years[$i] = $i;
+                $dates['year'][$i] = $i;
             }
         } else {
             for ($i = $var->type->_start_year; $i <= $var->type->_end_year; $i++) {
-                $years[$i] = $i;
+                $dates['year'][$i] = $i;
             }
         }
         $date = $var->type->getDateParts($var->getValue($vars, $index));
-?>
-<select name="<?php echo $var->getVarName() ?>[month]" id="<?php echo $var->getVarName() ?>[month]"><?php echo $this->_selectOptions($months, $date['month']) ?></select>
-<select name="<?php echo $var->getVarName() ?>[day]" id="<?php echo $var->getVarName() ?>[day]"><?php echo $this->_selectOptions($days, $date['day']) ?></select>
-<select name="<?php echo $var->getVarName() ?>[year]" id="<?php echo $var->getVarName() ?>[year]"><?php echo $this->_selectOptions($years, $date['year']) ?></select>
-<?php
+        
+        // TODO: use NLS to get the order right for the Rest Of The World
+        $date_parts = array('month', 'day', 'year');
+        foreach($date_parts as $part) {
+            $varname = $var->getVarName().$part; 
+            printf('<select name="%s" id="%s"%s>%s</select>',
+                   $varname,
+                   $varname,
+                   $this->_getActionScripts($form, $var, $index),
+                   $this->_selectOptions($dates[$part], $date[$part]));
+        }
+        
         if ($var->type->_picker && $GLOBALS['browser']->hasFeature('javascript')) {
             Horde::addScriptFile('open_calendar.js', 'horde');
             $imgId = $this->_genID($var->getVarName(), $index, false) . 'goto';
@@ -416,11 +458,15 @@
     {
         $values = $var->getValues();
         $prompt = $var->type->getPrompt();
-        $selected = $var->getValue($vars, $index);
-?><select <?php echo $this->_genID($var->getVarName(), $index) ?> name="<?php echo $var->getVarName() ?>"<?php if ($var->hasAction()) $this->_genActionScript($form, $var->_action, $var->getVarName(), $index) ?>>
-  <?php if (!empty($prompt)) { echo '<option value="">' . @htmlspecialchars($prompt, ENT_QUOTES, NLS::getCharset()) . '</option>'; } echo $this->_selectOptions($values, $selected) ?>
-  </select>
-<?php
+        if (!empty($prompt)) { 
+            $prompt = '<option value="">' . @htmlspecialchars($prompt, ENT_QUOTES, NLS::getCharset()) . '</option>';
+        }
+        printf('<select name="%s" id="%s"%s>%s%s</select>',
+               $var->getVarName(),
+               $this->_genID($var->getVarName(), $index),
+               $this->_getActionScripts($form, $var, $index),
+               $prompt,
+               $this->_selectOptions($values, $var->getValue($vars, $index)));
     }
 
     function _renderVarInput_mlenum(&$form, &$var, &$vars, $index = null)
@@ -481,10 +527,11 @@
         if (!$wasset) {
             $selected = $var->getDefault();
         }
-?><select multiple="multiple" size="<?php echo $var->type->size ?>" name="<?php echo $var->getVarName() ?>[]">
-  <?php echo $this->_multiSelectOptions($values, $selected) ?>
-  </select>
-<?php
+        printf('<select multiple="multiple" size="%s" name="%s" %s>%s</select>',
+               $var->type->size,
+               $var->getVarName(),
+               $this->_getActionScripts($form, $var, $index),
+               $this->_multiSelectOptions($values, $selected));
         echo "<br />\n" . _("To select multiple items, hold down the Control (PC) or Command (Mac) key while clicking.") . "\n";
     }
 
@@ -492,14 +539,16 @@
     {
         $values = $var->getValues();
         $value  = $var->getValue($vars, $index);
-        echo $this->_radioButtons($var->getVarName(), $values, $value);
+        $actions = $var->_getActionScripts($form, $var, $index);
+        echo $this->_radioButtons($var->getVarName(), $values, $value, $actions);
     }
 
     function _renderVarInput_set(&$form, &$var, &$vars, $index = null)
     {
         $values = $var->getValues();
         $value  = $var->getValue($vars, $index);
-        echo $this->_checkBoxes($var->getVarName(), $values, $value);
+        $actions = $var->_getActionScripts($form, $var, $index);
+        echo $this->_checkBoxes($var->getVarName(), $values, $value, $actions);
     }
 
     function _renderVarInput_link(&$form, &$var, &$vars, $index = null)
@@ -509,8 +558,10 @@
 
     function _renderVarInput_email(&$form, &$var, &$vars, $index = null)
     {
-?><input type="text" name="<?php echo $var->getVarName() ?>" value="<?php echo $var->getValue($vars, $index) ?>" />
-<?php
+        printf('<input type="text" name="%s" value="%s"%s />',
+               $var->getVarName(),
+               $value = $var->getValue($vars, $index),
+               $this->_getActionScripts($form, $var, $index));
     }
 
     function _renderVarInput_matrix(&$form, &$var, &$vars, $index = null)
@@ -566,24 +617,36 @@
 
     function _renderVarInput_password(&$form, &$var, &$vars, $index = null)
     {
-?><input type="password" name="<?php echo $var->getVarName() ?>" value="<?php echo $var->getValue($vars, $index) ?>" />
-<?php
+        printf('<input type="password" name="%s" value="%s"%s />',
+               $var->getVarName(),
+               $value = $var->getValue($vars, $index),
+               $this->_getActionScripts($form, $var, $index));
     }
 
     function _renderVarInput_emailconfirm(&$form, &$var, &$vars, $index = null)
     {
         $email = $var->getValue($vars, $index);
-?><input type="text" name="<?php echo $var->getVarName() ?>[original]" value="<?php $email['original'] ?>" /><br />
-  <input type="text" name="<?php echo $var->getVarName() ?>[confirm]" value="<?php $email['confirm'] ?>" />
-<?php
+        printf('<input type="text" name="%s[original]" value="%s"%s />',
+               $var->getVarName(),
+               $value = $email['original'],
+               $this->_getActionScripts($form, $var, $index));
+        printf('<input type="text" name="%s[confirm]" value="%s"%s />',
+               $var->getVarName(),
+               $value = $email['confirm'],
+               $this->_getActionScripts($form, $var, $index));
     }
 
     function _renderVarInput_passwordconfirm(&$form, &$var, &$vars, $index = null)
     {
         $password = $var->getValue($vars, $index);
-?><input type="password" name="<?php echo $var->getVarName() ?>[original]" value="<?php echo $password['original'] ?>" /><br />
-  <input type="password" name="<?php echo $var->getVarName() ?>[confirm]" value="<?php echo $password['confirm'] ?>" />
-<?php
+        printf('<input type="password" name="%s[original]" value="%s"%s />',
+               $var->getVarName(),
+               $value = $password['original'],
+               $this->_getActionScripts($form, $var, $index));
+        printf('<input type="password" name="%s[confirm]" value="%s"%s />',
+               $var->getVarName(),
+               $value = $password['confirm'],
+               $this->_getActionScripts($form, $var, $index));
     }
 
     function _renderVarInput_boolean(&$form, &$var, &$vars, $index = null)
@@ -833,7 +896,7 @@
         return $result;
     }
 
-    function _checkBoxes($name, $values, $checkedValues)
+    function _checkBoxes($name, $values, $checkedValues, $actions = '')
     {
         $result = '';
         if (!is_array($checkedValues)) {
@@ -842,20 +905,38 @@
         $i = 0;
         foreach ($values as $value => $display) {
             $checked = (in_array($value, $checkedValues)) ? ' checked="checked"' : '';
-            $result .= "<input id=\"${name}${i}\" type=\"checkbox\" name=\"${name}[]\" value=\"$value\"$checked /><label for=\"${name}${i}\">&nbsp;$display</label><br />";
+            $result .= sprintf('<input id="%s%s" type="checkbox" name="%s[]" value="%s"%s%s /><label for="%s%s">&nbsp;%s</label><br />',
+                               $name,
+                               $i,
+                               $name,
+                               $value,
+                               $checked,
+                               $actions,
+                               $name,
+                               $i,
+                               $display);
             $i++;
         }
 
         return $result;
     }
 
-    function _radioButtons($name, $values, $checkedValue = null)
+    function _radioButtons($name, $values, $checkedValue = null, $actions = '')
     {
         $result = '';
         $i = 0;
         foreach ($values as $value => $display) {
             $checked = (!is_null($checkedValue) && $value == $checkedValue) ? ' checked="checked"' : '';
-            $result .= "<input id=\"${name}${i}\" type=\"radio\" name=\"$name\" value=\"$value\"$checked /><label for=\"${name}${i}\">&nbsp;$display</label><br />";
+            $result .= sprintf('<input id="%s%s" type="radio" name="%s[]" value="%s"%s%s /><label for="%s%s">&nbsp;%s</label><br />',
+                               $name,
+                               $i,
+                               $name,
+                               $value,
+                               $checked,
+                               $actions,
+                               $name,
+                               $i,
+                               $display);
             $i++;
         }
 
@@ -886,7 +967,29 @@
             }
         }
     }
-
+    
+    function _getActionScripts(&$form, &$var, $index = null)
+    {
+        $actions = '';
+        if ($var->hasAction()) {
+            $varname = $var->getVarName();
+            $action =& $var->_action;
+            $triggers = $action->getTrigger();
+            if (!is_array($triggers)) {
+                $triggers = array($triggers);
+            }
+            $js = $action->getActionScript($form, $this, $varname, $index);
+            foreach ($triggers as $trigger) {
+                if ($trigger == 'onload') {
+                    $this->_addOnLoadJavascript($js);
+                } else {
+                    $actions .= ' ' . $trigger . '="' . $js . '"';
+                }
+            }
+        }
+        return $actions;
+    }
+    
     function _addOnLoadJavascript($script)
     {
         $this->_onLoadJS[] = $script;
-------------- next part --------------
A non-text attachment was scrubbed...
Name: sum_fields.php
Type: application/x-php
Size: 1282 bytes
Desc: not available
Url : http://lists.horde.org/archives/dev/attachments/20040306/3808a94e/sum_fields-0001.bin
-------------- next part --------------
A non-text attachment was scrubbed...
Name: conditional_enable.php
Type: application/x-php
Size: 1696 bytes
Desc: not available
Url : http://lists.horde.org/archives/dev/attachments/20040306/3808a94e/conditional_enable-0001.bin
-------------- next part --------------
/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
/**
 * Javascript to add events to form elements
 *
 * Copyright 2004 Matt Kynaston <matt at kynx.org>
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
 *
 * @author  Matt Kynaston <matt at kynx.org>
 * @package Horde
 */

/**
 * Adds the given event to an element. If the element already has script for
 * the event, the new event is appended.
 * 
 * @param       Element         obj             the element to add event to
 * @param       string          name            the name of the event
 * @param       string          onchange        the onchange javascript 
 */
function addEvent(obj, name, js)
{
    if (obj) {
        // get existing events
        eval('events = obj.' + name);
        events = (events) ? events.toString() : '';
        events = events.substring(
                    events.indexOf('{') + 1, 
                    events.lastIndexOf('}'));
        events = events.replace(/\n/g, '').split(';');
        
        // return events should always be last, and are overridden
        // by any added ones, so always return a Macromedia-style 
        // document.MM_retVal
        count = events.length;
        last = '';
        while (last == '') {
            last = events.pop();
            count--;
        }
        is_return = (last.indexOf('return ') != -1);
        if (js.indexOf('return ') != -1 && is_return) {
            events.push(js);
        }
        else {
            if (is_return) {
                events.push(js);
                events.push(last);
            }
            else {
                events.push(last);
                events.push(js);
            }
        }
        
        js = events.join(';'); 

        // assign new anonymous function to event
        func = new Function(js);
        return eval('obj.' + name + '=func'); 
    }
    else {
        return false;
    }
}

/**
 * Returns given value as a number, or zero if NaN
 * @param       mixed   val
 * @return      Number
 */
function toNumber(val) 
{
    if (isNaN(val)) {
        return 0;
    }
    else {
        return Number(val);
    }
}

/**
 * Sets the enabled state of one element based on the values of another
 * 
 * Takes four or more arguments, in the form...
 *   checkEnabled(source, target, true, value1, value2, value3...)
 *
 * @param   Element    src      the element to check
 * @param   string     target   the element to enable/disable
 * @param   boolean    enabled  whether to enable or disable the target
 * @param   mixed               the value to check against
 */
function checkEnabled() 
{
    if (arguments.length > 2) {
        objSrc = arguments[0];
        objTarget = objSrc.form.elements[arguments[1]];
        enabled = arguments[2];
        toggle = false;
        if (objTarget) {
            switch (objSrc.type.toLowerCase()) {
                case 'select-one' :
                    val = objSrc.options[objSrc.selectedIndex].value;
                    break;
                case 'select-multiple' :
                    val = new Array();
                    count = 0;
                    for (i=0; i<objSrc.length; i++) {
                        if (objSrc.options[i].selected) {
                            val[count] = objSrc.options[i].value;
                        }
                    }
                    break;
                case 'checkbox' :
                    if (objSrc.checked) {
                        val = objSrc.value;
                        toggle = true;
                    }
                default :
                    val = objSrc.value;
            }
            for (i=3; i<arguments.length; i++) {
                if (typeof(val) == 'object' && (arguments[i] in val)) {
                    toggle = true;
                    break;
                }
                else if (arguments[i] == val) {
                    toggle = true;
                    break;
                }
            }
            
            objTarget.disabled = (toggle) ? !enabled : enabled;
            if (!objTarget.disabled) {
                // objTarget.focus();
            }
        }
    }
}

/**
 * Sets the target field to the sum of a range of fields 
 *
 * Takes three or more arguments, in the form:
 *    sumFields(form, target, field1, field2, field3...)
 * @param       Form            objFrm          the form to check
 * @param       string          target          the name of the target element
 * @param       string                          one or more field names to sum
 */
function sumFields() 
{
    if (arguments.length > 2) {
        objFrm = arguments[0];
        objTarget = objFrm.elements[arguments[1]];
        sum = 0;
        if (objTarget) {
            for (i=2; i<arguments.length; i++) {
                objSrc = objFrm.elements[arguments[i]];
                if (objSrc) {
                    switch (objSrc.type.toLowerCase()) {
                        case 'select-one':
                            sum += toNumber(objSrc.options[objSrc.selectedIndex].value);
                            break;
                        case 'select-multiple' :
                            for (j=0; j<objSrc.length; j++) {
                                sum += toNumber(objSrc.options[j].value);
                            }
                            break;
                        case 'checkbox' :
                            if (objSrc.checked) {
                                sum += toNumber(objSrc.value);
                            }
                            break;
                        default :
                            sum += toNumber(objSrc.value);
                    }
                }
            }
            objTarget.value = sum;
        }
    }
}


More information about the dev mailing list