Gary Storey - My little corner of the internet

  • home
  • articles
  • blog
  • about
Home

Useful Javascript Routines

Gary — Wed, 06/18/2008 - 2:30pm

I decided I would post some javascript routines that I find extremely useful when I am coding. These are all cross-browser compliant and should work just by copying and pasting into any javascript file.

I apologize ahead of time for these routines not using the best variable names in the world and the differing styles I wrote them in (they were written over the course of many years). Also some were borrowed from other sources and re-written to suit my needs at the time.

Anyway, you are welcome to use them. Let me know what you think....

//////////////////////////////////////////////////////////////////
// Create Javascript prototypes
//////////////////////////////////////////////////////////////////
// Add a trim function
String.prototype.trim = function () { return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");}   

// Add a "has" function to an array.
// Allows you to check to see if a value is in an array
Array.prototype.has = function (value) {
   var zyz; 
   for (zyz=0; i < this.length; zyz++) {
       if (this[zyz] === value) {
            return true;
       }
    } 
    return false;
};
//////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////
// Create a more powerful "getElementByID"
//////////////////////////////////////////////////////////////////
// Allows you to get more than one element at a time
// Will return an array of objects
function e() {
 var elements = new Array();
 for (var zyz = 0; zyz < arguments.length; zyz++) {
  var element = arguments[zyz];
  if (typeof element == 'string')
   element = document.getElementById(element);
  if (arguments.length == 1)
   return element;
  elements.push(element);
 }
 return elements;
}


// getElementsByClass
// Should have been built into Javascript. "tag" is optional 
function getElementsByClass(searchClass,tag) {
 var classElements = new Array();
 if ( tag == null )
  tag = "*";
 var els = document.getElementsByTagName(tag);
 var elsLen = els.length;
 var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|e)");
 for (zyz = 0, zyzz = 0; zyz < elsLen; zyz++) {
  if ( pattern.test(els[zyz].className) ) {
   classElements[zyzz] = els[zyz];
   j++;
  }
 }
 return classElements;
}
//////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////
// Change CSS Classes
///////////////////////////////////////////////////////////////////////////////


//Adds a CSS class to an element 
function addClass(thisclassname,obj) {
 if (!hasClass(thisclassname,obj.className)) {
  obj.className +=" " + thisclassname;  
 }
}


// Removes a CSS class from an element
function removeClass(thisclassname,obj) {
 var oldclass = obj.className;
 var newclass = "",check ="";
 // Remove leading and trailing spaces
 oldclass = oldclass.trim();
 var allclasses = oldclass.split(" ");
 //convert to an array of classes
 for (var thisclass = 0; thisclass < allclasses.length; thisclass++) {
  // get the classname and trim it
  check = allclasses[thisclass];
  check = check.trim();
  if(check.toUpperCase() != thisclassname.toUpperCase()) {
   newclass += " " + allclasses[thisclass];  
  }
 }
 while(newclass.indexOf("  ") >-1) {
  newclass = newclass.replace("  "," ");
 }
 // Update the class for the object
 obj.className = newclass;
}


// verifys that "findclass" is in a list of "classnames"
// returns true or false
function hasClass(findclass,classnames) {
 var result = false;
 findclass=findclass.toUpperCase();
 classnames = classnames.toUpperCase();
 var pattern = new RegExp("(^|\\s)" + findclass +"(\\s|e)");
 if ( pattern.test(classnames) ) {
  result = true;
 }
return result;
}

///////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////
// Form Functions
///////////////////////////////////////////////////////////////////////////////

// Enables all form fields 
function enableFormFields() {
 for(var thisform=0;thisform < document.forms.length;thisform++) {
  for(var thisfield=0;thisfield < document.forms[thisform].elements.length;thisfield++) {
   document.forms[thisform].elements[thisfield].disabled=false;
  }
 }
}

function disableFormFields() {
 for(var thisform=0;thisform < document.forms.length;thisform++) {
  for(var thisfield=0;thisfield < document.forms[thisform].elements.length;thisfield++) {
   document.forms[thisform].elements[thisfield].disabled=true;
  }
 }
}

// takes a comma delimited list of IDs and enables them
function enableFields(strList) {
 var elements = strList.split(",");
 for (var zyz = 0; zyz < elements.length; zyz++) {
  var element = elements[zyz];
  if (typeof element == 'string') {
   try { document.getElementById(element).disabled = false; }    catch(er) {} 
  }
 }
}

// takes a comma delimited list of IDs and disables them
function disableFields(strList) {
 var elements = strList.split(",");
 for (var zyz = 0; zyz < elements.length; zyz++) {
  var element = elements[zyz];
  if (typeof element == 'string') {
   try { document.getElementById(element).disabled = true; } catch(er) {} 
  }
 }
}

// Hides all drop down lists. Sometimes necessary for IE6
function hideDropDown() {
 x=document.getElementByTagName("select");
 for (var zyz=0;zyz < x.length;zyz++) {
  x[zyz].style.display='none';
 }
}

// Shows all dropdown lists
function showDropDown() {
 x=document.getElementByTagName("select");
 for (var zyz=0;zyz < x.length;zyz++) {
  x[zyz].style.display='inline';
 }
}

// Read selected values from dropdown list
// returns a comma delimited string
function readSelectedValues(thissel) {
 var selValues="";
 for (var zyz=0; zyz < thissel.length; zyz++) {
  if (thissel[zyz].selected) {
      selValues+=thissel[zyz].value+", ";
     }
 }
 selValues=selValues.substring(0,selValues.length-2);
 return(selValues);
}

// Selects all values for a dropdown list
function selectAllOptions(selStr){
  var selObj = document.getElementById(selStr);
  for (var zyz=0; zyz < selObj.options.length; zyz++) {
    selObj.options[zyz].selected = true;
  }
}

// Removes all options from a dropdown list
function removeAllOptions(lst) {
 var el=e(lst);
 el.options.length=0;
}

// Checks to see if a drop down list has a specific value
function selectHasValue(sel,val) {
 var zyz,z;
 val = val.toUpperCase();
 if (typeof(sel)!="object") {
  sel=document.getElementById(sel);
 }
 zyz=0;
 while (zyz< sel.options.length) {
  z=sel.options[zyz].value;
  if(z.toUpperCase()==val) { return true; }   
  zyz++;
 }
return false;
}

// Adds an option to a drop down list
function addOption(selname,opttxt,optval) {
 var elSel=e(selname);
 var elOptNew = document.createElement('option');
 elOptNew.value=optval;
 elOptNew.text=opttxt;
 // try standards compliant; doesn't work try IE
   try {  elSel.add(elOptNew, null);   }  catch(ex) {  elSel.add(elOptNew);   }
}
///////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////
// Simple string functions
//////////////////////////////////////////////////////////////////

// Similar to VBScripts left and right functions
function left(str, n){
 if (n <= 0)
     return "";
 else if (n > String(str).length)
     return str;
 else
     return String(str).substring(0,n);
}

function right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

// Valid US Phone number 
function isValidPhone(strPhone) {
 var re= new RegExp("(\(\d{3}\)|\d{3})\s?\d{3}[- ]\d{4}");
 var retcode = false
 if (re.test(strPhone)) { retcode = true; }
 return retcode;
}

///////////////////////////////////////////////////////////////////////////////

Trackback URL for this post:

http://www.garystorey.com/trackback/14
  • Add new comment

Theme

User login

  • Create new account
  • Request new password

Donation

If you like what you see, please donate. Any contributions are appreciated.



  • home
  • articles
  • blog
  • about

© Copyright 2008 Gary Storey