These are just a few JS functions I wrote to make things easier at work. Couldn't find good ones on google so I wrote them myself.
A Bookmarkable 'reset forms' link:
Code:
javascript:for(x in document.getElementsByTagName("form")){document.getElementsByTagName("form")[x].reset();};
Print price from float or string (2 digits after decimal, truncate instead of rounding):
Code:
function PriceString(x){
var cost = parseFloat(x).toString();
return ((cost.indexOf(".")==-1?(cost+"."):(cost))+"00").replace(/^([0-9]*)\.([0-9]{2}).*/,
"$$$1.$2");
}
Substring CountCode:
/* String prototype to use with either below */
String.prototype.ssc = function(needle) {
return substr_count(this, needle);
}
/* Recursive substr_count */
function substr_count(haystack, needle) {
return haystack.indexOf(needle)==-1?0:substr_count(haystack.substr(haystack.indexOf(needle)+1), needle)+1;
}
/*Non-recursive version*/
function substr_count(haystack, needle) {
var count=0;
for(var x=0; haystack.indexOf(needle, x)!=-1; count++)
{
x=haystack.indexOf(needle, x)+1;
}
return count;
}
Random Alpha Numeric String of length x
Code:
function randomString(x) {
var randomstring = '';
for (var i=0; i<x; i++)
randomstring += "0123456789abcdefghiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXTZ".substr(Math.floor(Math.random() * 61),1);
return randomstring;
}
Hopefully you can use them or, even better, offer better solutions.
Please feel free to post other useful javascript functions in here too.