Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Will Rickards http://willrickards.net/

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS 

Javascript Manipulate Class Names

I often have to manipulate class names of objects in javascript.
But className can have multiple classes in it.
These functions deal with that.

   1  
   2  // ----------------------------------------------------------------------------
   3  // HasClassName
   4  //
   5  // Description : returns boolean indicating whether the object has the class name
   6  //    built with the understanding that there may be multiple classes
   7  //
   8  // Arguments:
   9  //    objElement              - element to manipulate
  10  //    strClass                - class name to add
  11  //
  12  function HasClassName(objElement, strClass)
  13     {
  14  
  15     // if there is a class
  16     if ( objElement.className )
  17        {
  18  
  19        // the classes are just a space separated list, so first get the list
  20        var arrList = objElement.className.split(' ');
  21  
  22        // get uppercase class for comparison purposes
  23        var strClassUpper = strClass.toUpperCase();
  24  
  25        // find all instances and remove them
  26        for ( var i = 0; i < arrList.length; i++ )
  27           {
  28  
  29           // if class found
  30           if ( arrList[i].toUpperCase() == strClassUpper )
  31              {
  32  
  33              // we found it
  34              return true;
  35  
  36              }
  37  
  38           }
  39  
  40        }
  41  
  42     // if we got here then the class name is not there
  43     return false;
  44  
  45     }
  46  // 
  47  // HasClassName
  48  // ----------------------------------------------------------------------------
  49  
  50  
  51  // ----------------------------------------------------------------------------
  52  // AddClassName
  53  //
  54  // Description : adds a class to the class attribute of a DOM element
  55  //    built with the understanding that there may be multiple classes
  56  //
  57  // Arguments:
  58  //    objElement              - element to manipulate
  59  //    strClass                - class name to add
  60  //
  61  function AddClassName(objElement, strClass, blnMayAlreadyExist)
  62     {
  63  
  64     // if there is a class
  65     if ( objElement.className )
  66        {
  67  
  68        // the classes are just a space separated list, so first get the list
  69        var arrList = objElement.className.split(' ');
  70  
  71        // if the new class name may already exist in list
  72        if ( blnMayAlreadyExist )
  73           {
  74  
  75           // get uppercase class for comparison purposes
  76           var strClassUpper = strClass.toUpperCase();
  77  
  78           // find all instances and remove them
  79           for ( var i = 0; i < arrList.length; i++ )
  80              {
  81  
  82              // if class found
  83              if ( arrList[i].toUpperCase() == strClassUpper )
  84                 {
  85  
  86                 // remove array item
  87                 arrList.splice(i, 1);
  88  
  89                 // decrement loop counter as we have adjusted the array's contents
  90                 i--;
  91  
  92                 }
  93  
  94              }
  95  
  96           }
  97  
  98        // add the new class to end of list
  99        arrList[arrList.length] = strClass;
 100  
 101        // add the new class to beginning of list
 102        //arrList.splice(0, 0, strClass);
 103        
 104        // assign modified class name attribute
 105        objElement.className = arrList.join(' ');
 106  
 107        }
 108     // if there was no class
 109     else
 110        {
 111  
 112        // assign modified class name attribute      
 113        objElement.className = strClass;
 114     
 115        }
 116  
 117     }
 118  // 
 119  // AddClassName
 120  // ----------------------------------------------------------------------------
 121  
 122  
 123  // ----------------------------------------------------------------------------
 124  // RemoveClassName
 125  //
 126  // Description : removes a class from the class attribute of a DOM element
 127  //    built with the understanding that there may be multiple classes
 128  //
 129  // Arguments:
 130  //    objElement              - element to manipulate
 131  //    strClass                - class name to remove
 132  //
 133  function RemoveClassName(objElement, strClass)
 134     {
 135  
 136     // if there is a class
 137     if ( objElement.className )
 138        {
 139  
 140        // the classes are just a space separated list, so first get the list
 141        var arrList = objElement.className.split(' ');
 142  
 143        // get uppercase class for comparison purposes
 144        var strClassUpper = strClass.toUpperCase();
 145  
 146        // find all instances and remove them
 147        for ( var i = 0; i < arrList.length; i++ )
 148           {
 149  
 150           // if class found
 151           if ( arrList[i].toUpperCase() == strClassUpper )
 152              {
 153  
 154              // remove array item
 155              arrList.splice(i, 1);
 156  
 157              // decrement loop counter as we have adjusted the array's contents
 158              i--;
 159  
 160              }
 161  
 162           }
 163  
 164        // assign modified class name attribute
 165        objElement.className = arrList.join(' ');
 166  
 167        }
 168     // if there was no class
 169     // there is nothing to remove
 170  
 171     }
 172  // 
 173  // RemoveClassName
 174  // ----------------------------------------------------------------------------
 175    

Javascript QuickSelect (Coordinated Textbox And ListBox)

In HTML, say you have a select element with all the states.
Unfortunately typing in this select box only works with the first letter.
So if you type P then A you don't select pennsylvania.
What I commonly do in this situation is to have what I call a quickselect textbox on the page as well.
This is a textbox and listbox that are coordinated.

   1  
   2  // in your onload event handler you need this
   3  
   4  // hookup event handlers and control references
   5  var objElement = document.getElementById('cboState');
   6  if ( objElement )
   7     {
   8     objElement.onchange = QuickSelect_Change;
   9     objElement.textbox = document.getElementById('txtState');
  10     if ( objElement.textbox )
  11        {
  12        objElement.textbox.onchange = QuickSelect_TextChange;
  13        objElement.textbox.onblur = QuickSelect_TextChange;
  14        objElement.textbox.onkeypress = QuickSelect_KeyPress;
  15        objElement.textbox.listbox = objElement;
  16        }
  17     }       
  18  
  19  // and now the functions
  20  
  21  // ----------------------------------------------------------------------------
  22  // QuickSelect_KeyPress
  23  //
  24  // Description : event handler for quick select textbox's key press event
  25  //    selects the appropriate item in the associated listbox control
  26  //
  27  // Arguments : none
  28  //
  29  // Dependencies : 
  30  //
  31  // History :
  32  // 2006.09.20 - WSR : created
  33  //
  34  function QuickSelect_KeyPress( e )
  35     {
  36  
  37  
  38     var strCompare = '';
  39     var numEntryLen;
  40     var strEntry;
  41     var objSelect = this.listbox;
  42     var numOptions = objSelect.options.length;
  43  
  44     var numCharCode;
  45     var elTarget;
  46  
  47     // get event if not passed
  48     if (!e) var e = window.event;
  49  
  50     // get character code of key pressed
  51     if (e.keyCode) numCharCode = e.keyCode;
  52     else if (e.which) numCharCode = e.which;
  53  
  54     // get target
  55     if (e.target) elTarget = e.target;
  56     else if (e.srcElement) elTarget = e.srcElement;
  57                                                
  58     // if form input field & it is a printable character
  59     if ( elTarget.nodeName.toUpperCase() == 'INPUT' && numCharCode >= 32 && numCharCode <= 126 )
  60        {
  61  
  62        strEntry = this.value + String.fromCharCode(numCharCode);
  63        numEntryLen = strEntry.length;
  64  
  65        // cycle through options
  66        for (var i = 0; i < numOptions; i++)
  67           {
  68  
  69           // get compare string from value same length as entered string
  70           strCompare = objSelect.options[i].value.substring(0, numEntryLen);
  71  
  72           // if value matches what is entered
  73           if (strEntry == strCompare)
  74              {
  75  
  76              // select this option
  77              objSelect.options[i].selected = true;
  78  
  79              // end loop
  80              break;
  81  
  82              }
  83  
  84           }
  85  
  86        // I usually add an error class when input is required and not filled in
  87        // this removes the class so the input is no longer marked as invalid
  88        // commented out as it isn't necessary for general purpose
  89        // RemoveClassName( this, 'error' );
  90  
  91        }
  92  
  93     }
  94  //
  95  // QuickSelect_KeyPress
  96  // ----------------------------------------------------------------------------
  97  
  98  
  99  // ----------------------------------------------------------------------------
 100  // QuickSelect_TextChange
 101  //
 102  // Description : event handler for quick select textbox's change & onblur events
 103  //    makes sure item in textbox is a value from list
 104  //
 105  // Arguments : none
 106  //
 107  // Dependencies : none
 108  //
 109  // History :
 110  // 2006.08.09 - WSR : created
 111  //
 112  function QuickSelect_TextChange()
 113     {
 114  
 115     var strCompare = '';
 116     var numEntryLen = this.value.length;
 117     var strEntry = this.value;
 118     var objSelect = this.listbox;
 119     var numOptions = objSelect.options.length;
 120  
 121     // cycle through options
 122     for (var i = 0; i < numOptions; i++)
 123        {
 124  
 125        // get compare string from value same length as entered string
 126        strCompare = objSelect.options[i].value.substring(0, numEntryLen);
 127  
 128        // if value matches what is entered
 129        if (strEntry == strCompare)
 130           {
 131  
 132           // select this option
 133           objSelect.options[i].selected = true;
 134  
 135           // end loop
 136           break;
 137  
 138           }
 139  
 140        }
 141  
 142     // copy code to textbox
 143     this.value = this.listbox.options[this.listbox.selectedIndex].value;
 144  
 145     // I usually add an error class when input is required and not filled in
 146     // this removes the class so the input is no longer marked as invalid
 147     // commented out as it isn't necessary for general purpose
 148     // RemoveClassName( this, 'error' );
 149  
 150     }
 151  //
 152  // QuickSelect_TextChange
 153  // ----------------------------------------------------------------------------
 154  
 155  
 156  // ----------------------------------------------------------------------------
 157  // QuickSelect_Change
 158  //
 159  // Description : event handler for quick select list box's change event
 160  //    updates the textbox with the selected value
 161  //
 162  // Arguments: none
 163  //
 164  // Dependencies :
 165  //
 166  // History :
 167  // 2006.08.09 - WSR : created
 168  //
 169  function QuickSelect_Change()
 170     {
 171  
 172     // copy code to textbox
 173     this.textbox.value = this.options[this.selectedIndex].value;
 174  
 175     }	
 176  //
 177  // QuickSelect_Change
 178  // ----------------------------------------------------------------------------
 179    


Javascript LookupControl

A lookup control is a common thing to have on many web pages. In this case we assume a textbox, a command button, and a label of some sort to display a description.

The HTML might look like this
   1  
   2  <label for="txtExistingClient">Client</label>
   3  <input id="txtExistingClient" name="txtExistingClient" type="text" size="15" maxlength="14" class="text uppercase" runat="server">
   4  <input id="cmdExistingClientLookup" name="cmdExistingClientLookup" type="button" value=" ? ">
   5  <span id="lblExistingClient"></span>


Here is a javascript function to call in the onload to setup that lookup control. And examples of the functions required.
   1  
   2  // ----------------------------------------------------------------------------
   3  // SetupLookupControl
   4  //
   5  // Description : sets up a lookup control by linking it to its 
   6  //    associated controls and hooking up the event handlers
   7  //
   8  // Arguments :
   9  //    strTextBoxID               : input type=text id
  10  //    strLookupButtonID          : input type=button id
  11  //    strLabelID                 : span of div id
  12  //    funcTextBoxOnChange        : function for textbox's onchange and onblur event
  13  //    funcLookupButtonOnClick    : function for lookup button's onclick event
  14  //
  15  // Dependencies : none
  16  //
  17  // History :
  18  // 2006.07.14 - WSR : created
  19  //
  20  function SetupLookupControl( strTextBoxID, strLookupButtonID, strLabelID, funcTextBoxOnChange, funcLookupButtonOnClick )
  21     {
  22  
  23     // get reference to lookup button
  24     var ctlLookupButton = document.getElementById(strLookupButtonID);
  25  
  26     // if lookup button was found
  27     if (ctlLookupButton)
  28        {
  29  
  30        // hookup event handlers and control references
  31        ctlLookupButton.onclick = funcLookupButtonOnClick;
  32        ctlLookupButton.textbox = document.getElementById(strTextBoxID);
  33  
  34        // if textbox was found
  35        if (ctlLookupButton.textbox)
  36           {
  37  
  38           // hookup event handlers and control references
  39           ctlLookupButton.textbox.onchange = funcTextBoxOnChange;
  40           ctlLookupButton.textbox.onblur = funcTextBoxOnChange;
  41           ctlLookupButton.textbox.label = document.getElementById(strLabelID);
  42  
  43           // init last value property of textbox
  44           if ( typeof ctlLookupButton.textbox.lastvalue == 'undefined' )
  45              ctlLookupButton.textbox.lastvalue = ''; 
  46  
  47           }
  48  
  49        }
  50  
  51     }
  52  //
  53  // SetupLookupControl
  54  // ----------------------------------------------------------------------------
  55  
  56  // ----------------------------------------------------------------------------
  57  // cmdTimekeeperLookup_click
  58  // Description: handler for requesting timekeeper selection button click event
  59  // Arguments: none
  60  // Dependencies:
  61  //    TimekeepQuery (lookup.js)
  62  //
  63  function cmdTimekeeperLookup_click()
  64     {
  65  
  66     // show timekeeper query window
  67     TimekeepQuery( this.textbox );
  68  
  69     // update timekeeper information
  70     this.textbox.onchange();
  71  
  72     // process default action
  73     return true;
  74  
  75     }
  76  //
  77  // cmdTimekeeperLookup_click
  78  // ----------------------------------------------------------------------------
  79  
  80  
  81  // ----------------------------------------------------------------------------
  82  // txtTimekeeper_change
  83  // Description: event handler for timekeeper textbox change event
  84  // Arguments: none
  85  // Dependencies:
  86  //    window.strTkprMask (masking.js)
  87  //    trim
  88  //    ApplyMask (masking.js)
  89  //    TimekeepLookup (lookup.js)
  90  //    UpdateElementText (shared.js)
  91  //
  92  function txtTimekeeper_change()
  93     {
  94  
  95     var strTimekeepName = '';
  96     var objXMLDOM;
  97     var nodField;
  98   
  99     // trim input
 100     this.value = this.value.trim();
 101    
 102     // if there was input
 103     if ( this.value.length > 0 )
 104        {
 105  
 106        // apply timekeep mask to textbox input
 107        ApplyMask( this, window.strTkprMask );
 108  
 109        // if inputted timekeeper is different from current timekeeper
 110        if ( this.lastvalue != this.value )
 111           {
 112  
 113           // request timekeeper information
 114           objXMLDOM = TimekeepLookup( this.value );
 115  
 116           // if XML DOM object returned
 117           if ( typeof objXMLDOM == 'object' )
 118              {
 119  
 120              // get field values
 121              nodField = objXMLDOM.selectSingleNode('//lastname');
 122              if (nodField != null)
 123                 strTimekeepName = nodField.firstChild.nodeValue;
 124  
 125              nodField = objXMLDOM.selectSingleNode('//firstname');
 126              if (nodField != null)
 127                 strTimekeepName = strTimekeepName + ', ' + nodField.firstChild.nodeValue;
 128  
 129              // update timekeeper
 130              this.lastvalue = this.value;
 131  
 132              }
 133           // if XML DOM object wasn't returned
 134           else
 135              {
 136  
 137              // indicate timekeeper was not found
 138              strTimekeepName = 'Timekeep \'' + this.value + '\' was not found.';
 139  
 140              // update timekeeper
 141              this.lastvalue = '';
 142  
 143              }
 144  
 145           // update document
 146           UpdateElementText( this.label, strTimekeepName );
 147  
 148           }
 149  
 150        }
 151     // if there was no input
 152     else
 153        {
 154  
 155        // clear the timekeep and display
 156        this.lastvalue = '';
 157        UpdateElementText( this.label, '' );
 158  
 159        }
 160  
 161     // process default action
 162     return true;
 163  
 164     }
 165  //
 166  // txtTimekeeper_change
 167  // ----------------------------------------------------------------------------

Javascript: Preventing Form Submit When Enter is Pressed

In a web page, normally pressing enter when any form element has focus will submit the form. This is often premature. When you have a checkbox selected you probably just want to check the checkbox, not submit the form. So I wrote some javascript to translate the enter into a tab when possible (IE) and prevent the form submit when translation isn't possible (non-IE).

First is the code in your onload event handler.
This sets up onkeydown if window.event is supported (IE) and onkeypress if not.
   1  
   2  var frmRequest = document.getElementById('frmRequest');
   3  if (frmRequest)
   4     {
   5     if (window.event)
   6        frmRequest.onkeydown = frmRequest_KeyDown;
   7     else
   8        frmRequest.onkeypress = frmRequest_KeyPress;
   9     }


Next are the actual event handlers.
Nothing really special here, just dealing with the different ways of accessing event properties.