Showing posts with label Java Script. Show all posts
Showing posts with label Java Script. Show all posts

November 26, 2012

Jason Overview - Cascade Dropdown Using JSON

Javascript
Below i have specified sample of cascaded Dropdown using JSON.

function fnDrpChange()
{
try
{
 
var countries =
{
    "table" :
    [
        {"countryid": "0", "countryname": "Japan"},
        {"countryid": "1", "countryname": "India"},
        {"countryid": "2", "countryname": "Pakistan"},
        {"countryid": "3", "countryname": "Srilanka"}
    ]
};
 
var listItems ="";
for (var i = 0; i < countries.table.length; i++) {
    listItems += "<option value='" + countries.table[i].countryid + "'>" + countries.table[i].countryname + "</option>";
}
document.getElementById("ddlcountries").innerHTML =listItems;
}
catch(e)
{
alert(e);
}
}
 
 
function fnCountryChange(countryid)
{
try
{
 
var states =
{
    "table" :
    [
        {"countryid": "1", "stateid": "1", "statename": "TamilNadu"},
        {"countryid": "1", "stateid": "2", "statename": "Andra"},
        {"countryid": "1", "stateid": "3", "statename": "Kerala"}
    ]
};
 
 
var listItems ="";
for (var i = 0; i < states.table.length; i++) {
if(countryid == states.table[i].countryid)
{
    listItems += "<option value='" + states.table[i].stateid + "'>" + states.table[i].statename + "</option>";
}
}
document.getElementById("ddlstates").innerHTML =listItems;
}
catch(e)
{
alert(e);
}
}

Click Here to See Demo

September 26, 2012

FIXED: "IE: Microsoft JScript runtime error: 'JSON' is undefined"


Recently, while i`m working with javascript i got the following error.

Microsoft JScript runtime error: 'JSON' is undefined

But, It was working in some others system.

Question is Why i got this error ?
After a Little Bit of Googling, i found the reason.
That is, In ie7 or lesser versions native implementation of JSON not supported.
>ie7 have a native implementation of JSON by default. For to use JSON in ie7 or lesser version you need to refer the below js file.

But some time you may get the same error in IE8 or greater versions, in this time you have to check your IE browser rendering in > IE7 standards mode or not. If it is not change to higher version or use the below solution like IE7.

The Solution that works for me was.

Create a script file of below code and call it before JSON object 
called.


var JSON;if(!JSON){JSON={}}(function(){'use strict';function f(n){return n<10?'0'+n:n}if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+f(this.getUTCMonth()+1)+'-'+f(this.getUTCDate())+'T'+f(this.getUTCHours())+':'+f(this.getUTCMinutes())+':'+f(this.getUTCSeconds())+'Z':null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key)}if(typeof rep==='function'){value=rep.call(holder,key,value)}switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null'}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null'}v=partial.length===0?'[]':gap?'[\n'+gap+partial.join(',\n'+gap)+'\n'+mind+']':'['+partial.join(',')+']';gap=mind;return v}if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==='string'){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v)}}}}v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+mind+'}':'{'+partial.join(',')+'}';gap=mind;return v}}if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' '}}else if(typeof space==='string'){indent=space}rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify')}return str('',{'':value})}}if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j}throw new SyntaxError('JSON.parse')}}}());

Source: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

September 22, 2012

Jquery - Validate Multiple input controls Inside a Parent

function fnValidateChildFields(parentElement, selector) {
    var isValid = true;
 
    //Get Required Elements inside "Parent Element" By using selector
    //It will return filtered elements.
    var elements = jQuery(parentElement).find(selector);
 
    //For Each all fields and do your stuff
    jQuery.each(elements, function () {
 
        // Do validation Here..
 
        /* SAMPLE VALIDATION STARTS HERE */
 
        alert(this.id);
        alert(this.value);
        alert(this.getAttribute('class'));
 
        // Required Field validation
        if (this.value.length == 0)
            isValid = false;
 
        /* SAMPLE VALIDATION ENDS HERE */
 
    });
 
    return isValid;
}
 
 
function fnValidatePageII() {
    var isValid = false;
    try {
 
        // Parent ID name
        var parentElement = "#divParentID"
 
        // Class Name, It is used to get classes that needs to be replaced.
        var selector = ".className"
 
        if (fnValidateChildFields(parentElement, selector) == true)
            isValid = true;
    }
    catch (e) {
        alert(e);
    }
    return isValid;
}

January 10, 2012

Trim Text boxes using java script

Why we need TextBox.Text.Trim() in server side code, We can achieve this from client side itself.
Just create a function like below and call it from "OnClientClick" of Save button, That's it.

   1:  function fnTrimTextBoxes()
   2:  {
   3:     document.getElementById('textBoxName').value = document.getElementById('textBoxName').value.replace(/^\s+|\s+$/g, "");
   4:  }