Categories
AngularJS Solutions Web

AngularJS – Filter to add Leading 0s to any Number

Lets say you want to display a list of numbers from 1 to n but want them to be displayed as 01 02 03 04 05… and not 1 2 3 4 5… Angular by default doesn’t have a filter for this.

Here is how you implement it:

Implement the filter in a module. Here we take the variable len to define how many 0s must be prepended to the number.
If len is 2 then 1 becomes 01
If len is 3 then 1 becomes 001
If len is 4 then 1 becomes 0001… so on and so forth

angular.module('myModule', [])
.filter('fixedLengthPrefix', function () {
return function (n, len) {
var num = parseInt(n, 10);
len = parseInt(len, 10);
if (isNaN(num) || isNaN(len)) {
return n;
}
num = ''+num;
while (num.length < len) { num = '0'+num; } return num; }; });

Now add the filter to the markup:

{{number | fixedLengthPrefix:2}}

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")){}