Categories
JavaScript Open Source Solutions Web

JavaScript Date Format YYYY-MM-DD

Here is a simple function that takes the input of JS Date and returns a string of format YYYY-MM-DD:

var getDateFromDateTime = function(date) {
date = new Date(date); //Using this we can convert any date format to JS Date
var mm = date.getMonth() + 1; // getMonth() is zero-based
var dd = date.getDate();
if(mm<10){ mm="0"+mm; } if(dd<10){ dd="0"+dd; } return [date.getFullYear(), mm, dd].join('-'); // padding };

Categories
JavaScript Open Source Solutions Web

Convert JavaScript Date format YYYYMMDD

Here is a simple function that takes the input of JS Date and returns a string of format YYYYMMDD:

var getDateFromDateTime = function(date) {
date = new Date(date); //Using this we can convert any date format to JS Date
var mm = date.getMonth() + 1; // getMonth() is zero-based
var dd = date.getDate();
if(mm<10){ mm="0"+mm; } if(dd<10){ dd="0"+dd; } return [date.getFullYear(), mm, dd].join(''); // padding };

Categories
JavaScript Open Source Web

AngularJS – Round off Number to Fixed Length of Fractions

Angular’s built in number filter allows one to specify the number of decimals that should be displayed.

The syntax is as follows:
{{val | number:<count>}}

Where val is the value to be displayed, number is the filtername and count is the number of decimals to be displayed.

For eg.:

If val is 1234.56789

{{val | number:2}}

Displays: 1234.56

{{val | number:0}}

Displays: 1235

{{val | number:4}}

Displays: 1234.5679

Categories
JavaScript jQuery Web

JQuery: Join JSON arrays

The simplest way to merge JSON arrays usning JQuery is to use the concat function.

var json1 = [{id: 1, name: "one"}];
var json2 = [{id: 2, name: "two"}, {id: 3, name: "three"}];
var finalObj = json1.concat(json2);

Here finalObj will contain an array of 3 objects:
[{id: 1, name: “one”},{id: 2, name: “two”}, {id: 3, name: “three”}]

Categories
JavaScript jQuery Web

JQuery Check if Element Exists – JS Helpers

JQuery Check if Element Exists using this simple piece of code. To check this in the current page, we need to check the length of the element returned by the JQuery selector, if it returns you something then the element must exists otherwise no.

if( $('#EleSelector').length ) { // use this if you are using id, replace EleSelector with the id
// it exists
}

if( $(‘.EleSelector’).length ) { // use this if you are using class, replace EleSelector with the id
// it exists
}

In case of plain javascript try this:

//you can use it for more advanced selectors
if(document.querySelectorAll("#EleSelector").length){}

if(document.querySelector("#EleSelector")){}

//you can use it if your selector has only an Id attribute
if(document.getElementById("EleSelector")){}