General.js
From Code Trash
Set Tab Index - In the order of appearance
var ho ='name,address,phone,city,state,zipcode'; ho = ho.split(',') for(i in ho) { if(document.getElementsByName(ho[i])[0]) document.getElementsByName(ho[i])[0].tabIndex = i+1 }
Reload Captcha
function recaptcha(ref,url)
{
document.getElementById(ref).src = url + Math.floor(Math.random()*9000)+'/'
}
Get Absolute position of an HTML Object
function findAbsolutePosition(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return [curleft,curtop];
//returns an array
}
Make key value pair for ajax post from html form - makeParam()
function makeParam(param)
{
var str = param.split(',')
var val='';
val += str[0] + '=' + str[1];
for(var i=2;i<str.length;i+=2)
val += "&" + str[i] + '=' + document.getElementById(str[i+1]).value
return val;
}
Trim text
In programming, trim is a string manipulation function or algorithm. The most popular variants of the trim function strip only the beginning or end of the string. Typically named ltrim and rtrim respectively.
This Javascript code trim implementation removes all leading and trailing occurrences of a set of characters specified. If no characters are specified it will trim whitespace characters from the beginning or end or both of the string.
Without the second parameter, Javascript function will trim these characters:
- " " (ASCII 32 (0x20)), an ordinary space.
- "\t" (ASCII 9 (0x09)), a tab.
- "\n" (ASCII 10 (0x0A)), a new line (line feed).
- "\r" (ASCII 13 (0x0D)), a carriage return.
- "\0" (ASCII 0 (0x00)), the NUL-byte.
- "\x0B" (ASCII 11 (0x0B)), a vertical tab.
You need to call trim('string') which will return the trimmed text. From FireFox 3.5 we have a built in trim function.
function trim(str, chars) {
return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
XMLHTTP object creation in a single line
function createAjax()
{
return window.XMLHttpRequest ? new XMLHttpRequest() : ( window.ActiveXObject ? new window.ActiveXObject('Microsoft.XMLHTTP') : null)
}
Check Empty Objects
function notEmpty(o){
for (var prop in o) {
if (o.hasOwnProperty(prop)) return true;
}
return false;
}
function isEmpty(o){
for (var prop in o) {
if (o.hasOwnProperty(prop)) return false;
}
return true;
}
Strip HTML Tags
This function is the php equivalent of the same name. Interesting...
function strip_tags(str)
{
var re= /<\S[^><]*>/g
str = str.replace(re, "")
return str;
}
Events
Get source element of an event
function getEventSource(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
return targ;
}
Key Code of keyboard event
function getEventKeyCode(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
alert('Character was ' + character);
}
Where is mouse, Get mouse position
Drag and Drop detailed
quirksmode.org is my handy site where i confirm most of my ideas. Often i flip its pages to upgrade myself because of browser compatibility. The drag and drop code was really nice. People should use it instead of using a framework. They can use frameworks but there might some times be clashes (overriding of objects) when using multiple frameworks like Jquery and mootools. So here is one good demonstration with which you can create your own drag and drop or customize by including jquery or another frameworks.
Validation
var Validator = {
isEmail : function(s) {
return this.test(s, '^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$');
},
isAbsUrl : function(s) {
return this.test(s, '^(news|telnet|nttp|file|http|ftp|https)://[-A-Za-z0-9\\.]+\\/?.*$');
},
isSize : function(s) {
return this.test(s, '^[0-9]+(%|in|cm|mm|em|ex|pt|pc|px)?$');
},
isId : function(s) {
return this.test(s, '^[A-Za-z_]([A-Za-z0-9_])*$');
},
isEmpty : function(s) {
var nl, i;
if (s.nodeName == 'SELECT' && s.selectedIndex < 1)
return true;
if (s.type == 'checkbox' && !s.checked)
return true;
if (s.type == 'radio') {
for (i=0, nl = s.form.elements; i<nl.length; i++) {
if (nl[i].type == "radio" && nl[i].name == s.name && nl[i].checked)
return false;
}
return true;
}
return new RegExp('^\\s*$').test(s.nodeType == 1 ? s.value : s);
},
isNumber : function(s, d) {
return !isNaN(s.nodeType == 1 ? s.value : s) && (!d || !this.test(s, '^-?[0-9]*\\.[0-9]*$'));
},
test : function(s, p) {
s = s.nodeType == 1 ? s.value : s;
return s == '' || new RegExp(p).test(s);
}
};
Check Filename Extension
function isnFile(filename) { filename = document.getElementsByName(filename)[0].value if(filename=='')return true; if (!/(\.(jpg|jpeg|gif))$/i.test(filename))return true else return false; }
Set Cookie and Get Cookie
function setCookie(c_name,value,expiredays) { var exdate=new Date(); exdate.setDate(exdate.getDate()+expiredays); document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) + "; path=/"; } function getCookie(c_name) { if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "="); if (c_start!=-1) { c_start=c_start + c_name.length+1; c_end=document.cookie.indexOf(";",c_start); if (c_end==-1) c_end=document.cookie.length; return unescape(document.cookie.substring(c_start,c_end)); } } return null; }
Round Decimal Number
function roundNumber(number,decimal_points) { if(!decimal_points) return Math.round(number); if(number == 0) { var decimals = ""; for(var i=0;i<decimal_points;i++) decimals += "0"; return "0."+decimals; } var exponent = Math.pow(10,decimal_points); var num = Math.round((number * exponent)).toString(); return num.slice(0,-1*decimal_points) + "." + num.slice(-1*decimal_points) } //roundNumber((p/100),2)
isbien and jaxerror
function aresponse(jax) { if(jax.responseText.indexOf('jaxtimeout')+1) { alert("Session time out. Please re-login"); return; } if(isbien(jax.responseText)) { if(arguments.length>1) alert(arguments[1]) else alert('Updated Successfully'); } else { if(arguments.length>2) alert(strip_tags(jax.responseText)) else alert("Unable to process this request"); } } function jaxerror(jax) { if(arguments.length>1) alert(strip_tags(jax.responseText)) else alert("Unable to process this request"); }
Ajax Timeout
function jsTimeout(jax) { jax = jax.responseText ? jax.responseText : jax; if(jax.indexOf('ajaxtimeout')+1){ alert("Session time out. Please re-login.");return true;} return false; } function isloggedout(jax) { if(jax.responseText.indexOf('ajaxtimeout')+1)return true; return false; }
Not Number
function notnumber(nami,msg) { if(isNaN(document.getElementById(nami).value)) jsalert(msg,nami); }
Delete This
function deleteThis(ref,box) { var str; str = ref if(isNaN(ref)) { if(!isSelected(ref)) { alert("Please select item(s) to delete"); return; } str = getSelected(ref) str = rtrim(str,',') } if(!confirm("Are you sure you want to delete?"))return request("id="+str,baseurl+"controller/delete/",0,0) }
MakeParamEx
function makeParamEx(str) { str = str.split(','); var sri=''; var nxt =''; var param =''; for(var i=0;i<str.length;i++) { sri = str[i].match(/^[a-z]+$/) if(sri) { param += '&'+sri; nxt = str[i+1].match(/^\[(.*)\]$/) if(nxt){ param += '=' + nxt[1]; i++; continue; } nxt = str[i+1].match(/\((.*)\)$/) if(nxt){ param += '=' + encodeURIComponent(window[nxt[1]]); i++; continue; } param += '=' + encodeURIComponent(getjsText(str[i+1])) i++; continue; } sri = str[i].match(/\/(.*)\//) if(sri)param += '&'+ sri[1] + '=' + encodeURIComponent(getjsText(sri[1])) } param = param.replace(/^\&/,'') return param; } var param = makeParamEx('command,[save_seo],jaxpost,[1],/lang/,/sim/,/title/,/keywords/,/description/,/description/,/id/');
Set Values from JSON
The response from the server is an object which is one record set to be populated. I provide the input name and the key in the object. So input name will be populated with its equivalent key value in the object.
// still experimenting function setvalues(obj,str) { str = str.split(','); var oye='' var tn='' for(var i=0;i<str.length;i+=2) { oye = document.getElementById(str[i]) tn = oye.tagName.toLowerCase() if(tn=='select') { setjsSelectedText(str[i],obj[str[i+1]]); continue; } if(tn=='input') { if(oye.type=='text') { // alert(obj[str[i+1]]) setvalue(str[i],obj[str[i+1]]); continue; } } } } // call: setvalues(so,'sfname,firstname,slname,lastname,saddress,address,scity,city,sstate,state,);
where first parameter is json and the rest are input names, key in the object
