Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Wednesday, May 20, 2015

Comparing arrays in Java Script

A sample on how to compare two arrays :


Array.prototype.diff = function(a) {
    return this.filter(function(i) {return a.indexOf(i) < 0;});
};
var a = ['b','c'];
var b = ['b','c','d','e','f'];
var temp = a.diff(b);
temp.length;

Credits : Nikhil

Monday, November 3, 2014

Javascript to get the current language of the browser


function getLanguageCode() {
    var lang;
    if (getQueryVariable("language")) {
        lang = getQueryVariable("language");
    } else if (navigator) {
        if (navigator.userLanguage) {
            lang = navigator.userLanguage;
        } else if (navigator.browserLanguage) {
            lang = navigator.browserLanguage;
        } else if (navigator.systemLanguage) {
            lang = navigator.systemLanguage;
        } else if (navigator.Language) {
            lang = navigator.Language;
        } else if (navigator.language) {
            lang = navigator.language;
        }
    }
    alert(lang);
}

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return false;
}

Credits : Amit Kumar 
Email : amitagl27@gmail.com

Tuesday, September 16, 2014

Detect the browser through javascript

In Cordys we do have a simple "system" variable which tells which browser we are using like below

system.isIE
system.isChrome

etc.,

But here the dependency would be system variable would be defined in a javascript in "application.js" which is a cordys platform javascript file.

To remove this dependency the following can be done

navigator.sayswho= (function(){
    var ua= navigator.userAgent, tem, 
    M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE '+(tem[1] || '');
    }
    if(M[1]=== 'Chrome'){
        tem= ua.match(/\bOPR\/(\d+)/)
        if(tem!= null) return 'Opera '+tem[1];
    }
    M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
    return M.join(' ');
})();

And you can use this piece of code like below

if(!navigator.sayswho.toLowerCase().indexOf("ie "))
 {
 charCode = (event.which) ? event.which : event.keyCode;
 windowEventCode = event;
 }else if (window.event)
 {
  charCode = window.event.keyCode;
  windowEventCode = window.event;
 }


Friday, August 1, 2014

Learnings from CORS : Call a webservice from other domains

Problem Statement :

We generally encounter a scenario where we have to access services which are not hosted locally (i.e., Other domain). This normally can't be achieved straight forwardly in html. We need to understand few points here which I will be explaining in this post.

References :

Explanation :

I would go with the assumption that one must know how to call a web service from html. If not the above reference would help in achieving this.

Note : A clear information that this is not possible in latest versions of chrome (I have tested only with browsers chrome and IE). This post is not meant for the applications which is using latest versions of chrome (http://bugs.jquery.com/ticket/4690 post would help you understand why).

Lets say you are using the same html file which is being explained in this post. Only difference being the gatewayURL which is the end point url being different.

How to solve it in IE :

Be it XMLHttpRequest or ajax request you can access services of cross domain using a browser property (this again depends on every client and also not secure). The property is as shown below in the image,



 After enabling this option one can access cross domain services in IE.

How to Enable in Chrome lower versions (I have chrome 16):

Although new versions of chrome doesn't support cross domain services at all but this can be achieved for lower versions of chrome using concept called "CORS". CORS stand for Cross Origin Resource Sharing. 

In Simple terms "Server has to authorize the client for cross domain accessing in case of chrome". This is not happening in IE as this is enabled at client side using settings of IE.

Problems/Resolution :

Possible errors from Chrome 16 are shown below :



Add below two properties to the website that you are using :

"Access-Control-Allow-Headers" with value "Content-Type"
"Access-Control-Allow-Origin" with value "*" (* generally represents allow any domain you have to google on how to give multiple domains, in general one domain is http://dhl-hyd1024)



Friday, February 28, 2014

setTimeout usage in javascript

Generally window.setTimeout or setTimeout is similar function. They perform call to a custom defined javascript function after specific amount of time.

There are browsers which makes the below line valid

setTimeout(callingAFunction(),400);

Which calls a function called "callingAFunction" after 400 milliseconds. But this function creates a problem in IE8 which gives a script error. Instead use like this,

setTimeout(callingAFunction,400);

Thursday, February 20, 2014

How to check where is syntax error in javascript?

By simply looking at a javascript file one cannot say where is the syntax error (if any). And there is no compiler as such during our development which will say that. We simply write DOM methods or functions in the javascript unlike Java (Eclipse is a tool which will validate the source code during development). But this is not available in javascript. However during development of any application in cordys there will be a place where you add events/javascript functions in any XForm. Cordys will be able to tell if the XForm has any errors but it won't tell where exactly the error is (eg., will not tell the line number of the error) which will make difficult for a developer to locate where exactly is the error,

There is an online website which will validate the javascript and will notify the error if there are any,

All you have to do is to copy the javascript and paste in the place provided in the website. A sample screen is shown below


And the website you are looking for is given below

http://www.javascriptlint.com/online_lint.php

On Click of the lint button it will show the errors if there are any in the javascript file.

Tuesday, December 17, 2013

Java Script : Date Format Utilities

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
Date.prototype.monthNames = [
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
];

Date.prototype.getMonthName = function() {
return this.monthNames[this.getMonth()];
};
Date.prototype.getShortMonthName = function () {
return this.getMonthName().substr(0, 3);
};

function convert(dateObj,fromFormat,toFormat) {
/*default the values 
dateObj default it to new Date();
fromFormat default it to UTC;
toFormat default it to UTC;
*/
var dateObj = dateObj;
var fromFormat = fromFormat;
var toFormat = toFormat;
if(!dateObj || dateObj=="")
dateObj = new Date();
debugger;
//if both fromFormat and toFormat is null
dateObj = new Date(Date.parse(dateObj));
if(!toFormat || toFormat=='' || toFormat=='CORDYS')
{
//return the dateObj in UTC Format
return dateObj.toISOString();
}
if(toFormat=='dd-MM-yyyy'){
var formattedDT = dateObj.getDate()+"-"+dateObj.getMonth()+"-"+dateObj.getFullYear();
return formattedDT;
}
if(toFormat=='yyyy-MM-dd'){
var formattedDT = dateObj.getFullYear()+"-"+dateObj.getMonth()+"-"+dateObj.getDate();
return formattedDT;
}
if(toFormat=='UTC'||toFormat=='GMT'){
return dateObj.toUTCString();
}
if(toFormat=='dd/MM/yyyy'){
var formattedDT = dateObj.getDate()+"/"+dateObj.getMonth()+"/"+dateObj.getFullYear();
return formattedDT;
}
if(toFormat=='yyyy/MM/dd'){
var formattedDT = dateObj.getFullYear()+"/"+dateObj.getMonth()+"/"+dateObj.getDate();
return formattedDT;
}
if(toFormat=='dd-MMM-yyyy'){
var formattedDT = dateObj.getDate()+"-"+dateObj.getShortMonthName()+"-"+dateObj.getFullYear();
return formattedDT;
}
if(toFormat=='dd MMM yyyy'){
var formattedDT = dateObj.getDate()+" "+dateObj.getShortMonthName()+" "+dateObj.getFullYear();
return formattedDT;
}
var format = dateObj.getFullYear()+"-";
format += dateObj.getMonth()+"-";
format += dateObj.getDate();
return dateObj.toJSON();
}
function convertDate(){
$("#convertedFormat").html(convert($('#custDate').val(),'',$('#ipDateFormat').val()));
}
</script>
</head>
<body>
<font style="font-family:Trebuchet MS;font-size:14px;width:100%;">Date Format <input id="ipDateFormat"></input></font><br/>
<input id="custDate" type="date" title="Please enter Date"></input><br/>
<button id="convertFormat" onclick="convertDate()">Convert Format</button><br/>
<div id="convertedFormat" style="font-family:Trebuchet MS;font-size:14px;width:100%;"><div>
</body>
</html>

Java Script : Convert Ascii value to character

String.fromCharCode(charCode)

Java Script : Mandatory mark for fields

function mandatory(control)
{
 if(cordys.getTextContent(control.getLabel()).indexOf('*')<0)
     control.setLabel(cordys.getTextContent(control.getLabel())+" <font color='RED'>*</font>");
}

Java Script : Delete Cookie

function deleteCookie(cookieName,cookiePath)  {
  var path = window.location.pathname;
  document.cookie = cookieName + "=; path="+cookiePath+";expires=Thu, 01 Jan 1970 00:00:01 GMT;"  
 }