RSS

Category Archives: JavaScript

Restrict text field to accept only numeric number in javascript

First write the following two functions:

function extractNumber(obj, decimalPlaces, allowNegative)
{
 var temp = obj.value;

 // avoid changing things if already formatted correctly
 var reg0Str = '[0-9]*';
 if (decimalPlaces > 0) {
  reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
 } else if (decimalPlaces  0 && temp.charAt(0) == '-';
  var reg2 = /-/g;
  temp = temp.replace(reg2, '');
  if (hasNegative) temp = '-' + temp;
 }

 if (decimalPlaces != 0) {
  var reg3 = /\./g;
  var reg3Array = reg3.exec(temp);
  if (reg3Array != null) {
   // keep only first occurrence of .
   //  and the number of places specified by decimalPlaces or the entire string if decimalPlaces  0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
   temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
  }
 }

 obj.value = temp;
}
function blockNonNumbers(obj, e, allowDecimal, allowNegative)
{
 var key;
 var isCtrl = false;
 var keychar;
 var reg;

 if(window.event) {
  key = e.keyCode;
  isCtrl = window.event.ctrlKey
 }
 else if(e.which) {
  key = e.which;
  isCtrl = e.ctrlKey;
 }

 if (isNaN(key)) return true;

 keychar = String.fromCharCode(key);

 // check for backspace or delete, or if Ctrl was pressed
 if (key == 8 || isCtrl)
 {
  return true;
 }

 reg = /\d/;
 var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
 var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;

 return isFirstN || isFirstD || reg.test(keychar);
}

Then use the above functions from your input field as follows:

<input type="text" onblur="extractNumber(this,-1,false);" onkeyup="extractNumber(this,-1,false);" onkeypress="return blockNonNumbers(this, event, true, false);" />
 
Leave a comment

Posted by on June 23, 2011 in JavaScript, Mixed

 

Tags:

Validate numbers in JavaScript

Check your input with the following function:

function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}

You can use another function:

function IsNumeric(input)
{
return (input - 0) == input && input.length > 0;
}

The (input – 0) expression forces JavaScript to do type coercion on your input value; it must first be interpreted as a number for the boolean compare. If that conversion to a number fails, the expression will result in NaN. Then this numeric result is compared to the original value you passed in. Since the left hand side is a number, type coercion is again used. They should always be the same (always true), but there’s a special rule that says NaN is never equal to NaN, and so a value that can’t be converted to a number will always return false. The check on the length is of course for the empty string special case. In summary, if you want to know if a value can be converted to a number, actually try to convert it to a number.

Note that it falls down on your 0x89f test, but that’s because in many environments that’s an okay way to define a number literal. If you want to catch that specific scenario you could add an additional check. Even better, if that’s your reason for not using isNaN() then just wrap your own function around isNaN() that can also do the additional check.

Here is another one:

function isNumeric(input) {
var number = /^\-{0,1}(?:[0-9]+){0,1}(?:\.[0-9]+){0,1}$/i;
var regex = RegExp(number);
return regex.test(input) && input.length>0;
}

Integer value can be verified by:

function isNumeric(value) {
var bool = isNaN(+value));
bool = bool || (value.indexOf('.') != -1);
bool = bool || (value.indexOf(",") != -1);
return !bool;
}
 
Leave a comment

Posted by on June 21, 2011 in JavaScript, Mixed

 

Using Namespaces to Prevent Conflicts

If you’re doing an extensive amount of raw JavaScript coding and suspect that additions could be made to the same pages you’re working on, you can prevent any future conflicts with your code by giving your code its own namespace.

Object-oriented JavaScript implements namespace-like principles due to the fact that properties and methods are declared inside of objects, thus there are less likely to be conflicts. A conflict could arise, however, through object names. And very likely, the conflict will occur “silently”, thus you may not be alerted to the issue immediately.

You can prevent all conflicts by creating a unique namespace. Let’s use the showStatistics function to demonstrate how we can encapsulate code into its own namespace:

if (typeof MY == "undefined") {
  MY = new Object();
  MY.CUSTOM = new Object();
}

MY.CUSTOM.namespace = function() {
  function showStatistics(args) {
    document.write("

Name: " + args.name); document.write("Team: " + args.team); if (typeof args.position === "string") { document.write("Position: " + args.position); } if (typeof args.average === "number") { document.write("Average: " + args.average); } if (typeof args.homeruns === "number") { document.write("Home Runs: " + args.homeruns); } if (typeof args.rbi === "number") { document.write("Runs Batted In: " + args.rbi + "

"); } } showStatistics({ name: "Mark Teixeira", team: "New York Yankees", position: "1st Base", average: .284, homeruns: 32, rbi: 101 }); } MY.CUSTOM.namespace();

The first few lines create the namespace by checking to see if the “MY” object already exists. This object can be whatever you want it to be. Just pick a name that you don’t think will ever be used again. After the MY object is created, we are then able to create the “CUSTOM” object as a property of the MY object. Then our namespace function becomes a method of the MY.CUSTOM object. Keep in mind that “MY”, “CUSTOM” and “namespace” can each be your own custom names. I chose these for demonstration purposes. They could be CHEESEBURGER.ONIONS.pickles if you want!

The showStatistics function is exactly the same as in the example earlier that utilizes an object literal to pass in the values. But in this case, the entire function, including the object literal, is encapsulated inside my.custom.namespace. The last line invokes the entire function using dot notation, and the function runs exactly the same as it normally would, except that it is protected from conflicting with another function called “showStatistics”.

 
Leave a comment

Posted by on June 13, 2011 in JavaScript, Mixed

 

Contextual Targeting of DOM Elements

There are sometimes instances where you need to traverse the DOM and gain access to a specific element, or group of elements, but due to certain restrictions, you may not have direct access to the elements via a CSS class name or ID in the HTML code. This might be because of user-generated content produced through a rich text editor, or dynamic content pulled from a database.

Whatever the case, it’s not impossible to access those unidentified DOM elements via JavaScript. Using what I call “contextual targeting”, you can gain access to, and modify, almost any element in the DOM. As long as you have a map of the general template that contains the element you want to target, you can access that element and manipulate it the same way you would an element that has a class name or ID.

Let’s create some basic HTML code that will serve as our example page:

<div id="header">
  <h1>Site Title</h1>
</div>
<div id="sidebar">
  <ul>
    <li><a href="#">Testing</a></li>

    <li><a href="#">Testing</a></li>
    <li><a href="#">Testing</a></li>
    <li><a href="#">Testing</a></li>

    <li><a href="#">Testing</a></li>
    <li><a href="#">Testing</a></li>
  </ul>

</div>
<div id="content">
  <h2>Page Title</h2>
  <p><a href="#">Lorum Ipsum link here</a>. Pellentesque habitant morbi
     tristique senectus et netus et malesuada fames ac turpis egestas.
     Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet,
     ante. Donec eu libero sit amet quam egestas semper.
     Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
     Pellentesque habitant morbi tristique senectus et netus et malesuada
     fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae,
     ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam
     egestas semper. Aenean ultricies mi vitae est. Mauris
     placerat eleifend leo.</p>

  <p><span style="color: red;">Pellentesque habitant morbi</span>
    tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum
    tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec
    eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est.
    Mauris placerat eleifend leo. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
    feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit
    amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat
    eleifend leo.</p>
</div>
<div id="footer">
   <p>Copyright | <a href="#">contact</a> | <a href="#">policy</a> |
      <a href="#">privacy</a></p>

</div>

Using the HTML code above, if we wanted to target all the anchor tags on the page, we could collect them and manipulate them like this:

var myLinkCollection = document.getElementsByTagName("a");

for (i=0;i<myLinkCollection.length;i++) {
  // do something with the anchor tags here
}

If we wanted to target only the anchor tags in the footer, however, we would target them based on their context, or surrounding elements, like this:

var myFooterElement = document.getElementById("footer");
var myLinksInFooter = myFooterElement.getElementsByTagName("a");
for (i=0;i<myLinksInFooter.length;i++) {
  // do something with footer anchor tags here
} 

The first line grabs a reference to the footer element. The second line collects all anchor tags inside the footer. Then we loop through them and do what we want with them. Thus, they are accessible even though they are not grouped via class names.

You can accomplish the same thing by using node properties, as shown below.

var myLinkCollection = document.getElementsByTagName("a");

for (i=0;i<myLinkCollection.length;i++) {
  if (myLinkCollection[i].parentNode.parentNode.id === "footer") {
    // do something with footer anchor tags here
  }
} 

Similar code could be used to target the lone anchor tag inside the “content” section.

We could also limit our anchor tag search to include only tags that have the href attribute set, so as to avoid finding any in-page links. We do this by using the getAttribute method:

var myLinkCollection = document.getElementsByTagName("a");

for (i=0;i<myLinkCollection.length;i++) {
  if (myLinkCollection[i].getAttribute("href")) {
    // do something with the anchor tags here
  }
}

Finally, you’ll notice that there is a tag with an inline style. The inline style could have been generated through a content management system, so you may not have the ability to edit it directly. You can target all elements with inline styles like this:

var myLinkCollection = document.getElementsByTagName("span");

for (i=0;i<myLinkCollection.length;i++) {
  if (myLinkCollection[i].getAttribute("style")) {
    // do something with all anchors that have inline styles
  }
}  
 
Leave a comment

Posted by on June 13, 2011 in JavaScript, Mixed

 

Object Literals to Pass Optional Arguments

Instead of passing the large number of arguments in the conventional fashion, which could unnecessarily complicate the function, you can pass just one argument which ends up being a collection of arguments declared in an object literal.

Let’s look, first of all, at how we might do this in the typical manner, so we can see the contrast:

function showStatistics(name, team, position, average, homeruns, rbi) {
  document.write("

Name: " + arguments[0]);
  document.write("Team: " + arguments[1]);

  if (typeof arguments[2] === "string") {
    document.write("Position: " + position);
  }
  if (typeof arguments[3] === "number") {
    document.write("Batting Average: " + average);
  }
  if (typeof arguments[4] === "number") {
    document.write("Home Runs: " + homeruns);
  }
  if (typeof arguments[5] === "number") {
    document.write("Runs Batted In: " + rbi + "

");
  }
}
showStatistics("Mark Teixeira");
showStatistics("Mark Teixeira", "New York Yankees");
showStatistics("Mark Teixeira", "New York Yankees", "1st Base", .284, 32, 101);

The function above can take up to 6 arguments. The first two arguments are mandatory, so inside the function, we don’t check for their existence. The last 4 arguments are not mandatory, so we only display their values if they exist.

We call the function 3 different times (last 3 lines), with different numbers of arguments each time. You can see that if the number of passed arguments was in the dozens, or more, the code could look a little messy, and would be harder to maintain, or read.

Now let’s look at the same code using object literals to pass the arguments:

function showStatistics(args) {
  document.write("Name: " + args.name);
  document.write("Team: " + args.team);
  if (typeof args.position === "string") {
    document.write("Position: " + args.position);
  }
  if (typeof args.average === "number") {
    document.write("Average: " + args.average);
  }
  if (typeof args.homeruns === "number") {
    document.write("Home Runs: " + args.homeruns);
  }
  if (typeof args.rbi === "number") {
    document.write("Runs Batted In: " + args.rbi);
  }
}

showStatistics({
  name: "Mark Teixeira"
});

showStatistics({
  name: "Mark Teixeira",
  team: "New York Yankees"
});

showStatistics({
  name: "Mark Teixeira",
  team: "New York Yankees",
  position: "1st Base",
  average: .284,
  homeruns: 32,
  rbi: 101
});

Technically, this second method of passing the arguments might require a little bit more code, but with a large collection of arguments, there are a few advantages.

First, the function itself is simplified because it accepts only one argument (args), which is a collection of all the values passed from the object literal (name, team, position, etc). Plus, the actual argument values are easy to read, and can easily be understood, updated, or modified, since the correlation between the values and the argument references are more direct.

If the function required only a small number of arguments, then this method would not be necessary, and might actually have the opposite effect. So, use this technique sparingly, and only in situations where you foresee the collection of arguments being hard to maintain over time.

 
Leave a comment

Posted by on June 13, 2011 in JavaScript, Mixed

 

Explaining JavaScript Scope And Closures

Scope

Scope refers to where variables and functions are accessible, and in what context it is being executed. Basically, a variable or function can be defined in a global or local scope. Variables have so-called function scope, and functions have the same scope as variables.

Global Scope

When something is global means that it is accessible from anywhere in your code. Take this for example:

var monkey = "Gorilla";

function greetVisitor () {
	return alert("Hello dear blog reader!");
}

If that code was being run in a web browser, the function scope would be window, thus making it available to everything running in that web browser window.

Local Scope

As opposed to the global scope, the local scope is when something is just defined and accessible in a certain part of the code, like a function. For instance;

function talkDirty () {
	var saying = "Oh, you little VB lover, you";
	return alert(saying);
}
alert(saying); // Throws an error

If you take a look at the code above, the variable saying is only available within the talkDirty function. Outside of it it isn’t defined at all. Note of caution: if you were to declare saying without the var keyword preceding it, it would automatically become a global variable.

What this also means is that if you have nested functions, the inner function will have access to the containing functions variables and functions:

function saveName (firstName) {
	function capitalizeName () {
		return firstName.toUpperCase();
	}
	var capitalized = capitalizeName();
	return capitalized;
}
alert(saveName("Robert")); // Returns "ROBERT"

As you just saw, the inner function capitalizeName didn’t need any parameter sent in, but had complete access to the parameter firstName in the outer saveName function. For clarity, let’s take another example:

function siblings () {
	var siblings = ["John", "Liza", "Peter"];
	function siblingCount () {
		var siblingsLength = siblings.length;
		return siblingsLength;
	}
	function joinSiblingNames () {
		return "I have " + siblingCount() + " siblings:\n\n" + siblings.join("\n");
	}
	return joinSiblingNames();
}
alert(siblings()); // Outputs "I have 3 siblings: John Liza Peter"

As you just saw, both inner functions have access to the siblings array in the containing function, and each inner function have access to the other inner functions on the same level (in this case, joinSiblingNames can access siblingCount). However, the variable siblingsLength in the siblingCount is only available within that function, i.e. that scope.

Closures

Now when you hopefully have gotten a better grasp of what scope is, let’s add closures to the mix. Closures are expressions, usually functions, which can work with variables set within a certain context. Or, to try and make it easier, inner functions referring to local variables of its outer function create closures. For instance:

function add (x) {
	return function (y) {
		return x + y;
	};
}
var add5 = add(5);
var no8 = add5(3);
alert(no8); // Returns 8

Whoa, whoa! What just happened? Let’s break it down:

  1. When the add function is called, it returns a function.
  2. That function closes the context and remembers what the parameter x was at exactly that time (i.e. 5 in the code above)
  3. When the result of calling the add function is assigned to the variable add5, it will always know what x was when it was initially created.
  4. The add5 variable above refers to a function which will always add the value 5 to what is being sent in.
  5. That means when add5 is called with a value of 3, it will add 5 together with 3, and return 8.

So, in the world of JavaScript, the add5 function actually looks like this in reality:

function add5 (y) {
	return 5 + y;
}

The Infamous Loop Problem

How many times have you created some sort of loop where you wanted to assign the value of i in some way, e.g. to an element, and found out it just returned the last value i had?

Incorrect Reference

Let’s take a look at this faulty code, which creates 5 a elements, adds the value of i as a text to each element and an onclick which is expected to alert the value of i for that link, i.e. the same value as in the a element’s text. It then appends them to your document body:

function addLinks () {
	for (var i=0, link; i

Each a element gets the correct text, i.e. “Link 0″, “Link 1″ and so on. But whichever link you click, it alerts the number “5″. Oh my God, why? The reason for this is that the variable i get its value increased with 1 for each iteration of the loop, and since the onclick event isn’t being executed, just applied to the a element, it adds up.

Therefore, the loop continues until i is 5, which is the last value of i before the function addLinks exits. Then, whenever the onclick event is actually being triggered, it takes the last value of i.

Working Reference

What you want to do instead is create a closure, so that when you apply the value of i to the onclick event of the a element, it gets the exact value of i at just that moment in time. Like this:

function addLinks () {
	for (var i=0, link; i<5; i++) {
		link = document.createElement("a");
		link.innerHTML = "Link " + i;
		link.onclick = function (num) {
			return function () {
				alert(num);
			};
		}(i);
		document.body.appendChild(link);
	}
}
window.onload = addLinks;

Here is another version of addLinks():

function addLinks () {

for (var onclick = function(num){return function(){alert(num)}}, i=0, link; i<5; i++) {

link = document.createElement("a");

link.innerHTML = "Link " + i;

link.onclick = onclick(i);

document.body.appendChild(link);

}

};

onload = addLinks;

With this code, if you click the first a element it will alert “0″, the second “1″ etc; just what you probably expected with the first code I showed you to do. The solution here is that the inner function of what’s applied to the onclick event create a closure where it references the parameter num, i.e. what the i variable is at just that time.

That function then closes with that value safely tucked away, and can then return its corresponding number when the onclick event is being called.

Self-Invoking Functions

Self-invoking functions are functions who execute immediately, and create their own closure. Take a look at this:

(function () {
	var dog = "German Shepherd";
	alert(dog);
})();
alert(dog); // Returns undefined

Ok, so the dog variable was only available within that context. Big deal, man, hidden dogs… But, my friends, this is where it becomes really interesting!

Yahoo JavaScript Module Pattern

The gist of the pattern is that it uses a self-invoking function to create a closure, hence making it possible to have private and public properties and methods. A simple example:

var person = function () {
	// Private
	var name = "Robert";
	return {
		getName : function () {
			return name;
		},
		setName : function (newName) {
			name = newName;
		}
	};
}();
alert(person.name); // Undefined
alert(person.getName()); // "Robert"
person.setName("Robert Nyman");
alert(person.getName()); // "Robert Nyman"

The beauty of this is that you now can decide on your own what will be publicly visible for your object (and can be overwritten), and what is private and no one can access nor alter. The variable name above is hidden outside the context of the function, but accessible from the returned getName respectively setName functions, since they create closures where they have a reference to the name variable.

 
Leave a comment

Posted by on June 13, 2011 in JavaScript, Scopes and Closures

 

Closures to Extend Variable Scope

Closures in JavaScript are a fairly straightforward concept, and have been discussed online in a number of in-depth articles. The fact that they are straightforward doesn’t necessarily mean they’re simple however, as seen by the extensive articles that cover the subject. To create a closure, you nest a function inside of a function. That inner function has access to all variables in its parent function’s scope. This comes in handy when creating methods and properties in object oriented scripts. Here is a simple example that demonstrates the use of a closure:

function myObject() {
  this.property1 = "value1";
  this.property2 = "value2";
  var newValue = this.property1;
 this.performMethod = function() { myMethodValue = newValue; return myMethodValue; };
  }
  var myObjectInstance = new myObject();
  alert(myObjectInstance.performMethod());

The key portions of the script are the nested anonymous function are highlighted in bold and the method call in the alert function (last line). Because the method in the alert is actually calling a nested function, that method is able to read the value of the variable called newValue, even thought that variable is not within the scope of the anonymous function, or method.

Developers use closures all the time, probably unknowingly, since a closure is created any time an anonymous function is nested inside another function and utilizes variables from the parent function’s scope. The power of the closure is revealed when that method (the inner function) is called, and values that normally wouldn’t be accessible are within “regional” scope and are thus able to be used as any other value.

 
Leave a comment

Posted by on June 13, 2011 in JavaScript, Scopes and Closures