JavaScript: Using Underscore.js to handle collections

As I was having to match two collections of objects in a project I was working on I faded out for a minute or two thinking of LINQ and the simplicities of working with collections in C#. I then woke up to horrid, nested for-loops in javascript and realized I had to do something. I googled around and found Underscore.js. This was a simple and fast javascript library for working with collections.

I made an example where I had a list of people and another list with some of the people I had already saved. I wanted a new list with the non-saved people. One way is to create a new list, loop over the list with all the people and within it loop through the list with saved people and compare it and add to the new list.
Or you can do as I did with Underscore.js:

http://jsfiddle.net/maffelu/2jCH9/

var people = [
    {name: "Magnus", "Age": 30},
    {name: "Fadangus", "Age": 29},
    {name: "Laban", "Age": 42},
    {name: "Bintje", "Age": 3}
    ];

var saved = [
   {name: "Fadangus", "Age": 29}
    ];

var result = _.filter(people, function(p)
                      {
                         return _.findWhere(saved, p) === undefined;
                      });

//result: [Object { name="Magnus", Age=30}, Object { name="Laban", Age=42}, Object { name="Bintje", Age=3}]

Javascript: Looping through radio buttons without jQuery

There are times when you don’t have access to a third-party library such as jQuery to make life easy and those are the times where you regret not paying any attention to how actual javascript works. Going through radio buttons with jQuery is very easy, but with javascript it is a little bit more unclear if you haven’t done it before.

I’m going to show you a very simple example where I have four radio buttons and I want to know which one is selected:

index.htm

<!DOCUMENT html>
<html>
	<head>
		<title>Javascript Radio Button Demo</title>
		<script type="text/javascript" src="MyScript.js"></script>
	</head>
	<body>
		<h1>My Form with radio buttons!</h1>
		<form id="MyForm" name="MyForm" action="#" method="GET">
			<p><input type="radio" name="direction" value="north"> North</p>
			<p><input type="radio" name="direction" value="east"> East</p>
			<p><input type="radio" name="direction" value="south"> South</p>
			<p><input type="radio" name="direction" value="west"> West</p>
			
			<p><input type="submit" name="submit" value="Submit"></p>
		</div>
	</body>
</html>

MyScript.js

window.onload = function()
{
	//Fetch the form element
	var form = document.getElementById("MyForm");
	
	//Bind the 'onsubmit' event to an anonymous function
	form.onsubmit = function()
	{
		//Find out how many radio buttons you have
		var numberOfDirections = form.direction.length;
		
		//Loop through the radio buttons
		for(var i = 0; i < numberOfDirections; i++)
		{
			//Select a radio button
			var direction = form.direction[i];
			
			//Check if the radio button is checked
			if(direction.checked)
			{
				alert("You selected " + direction.value);
			}
		}
		
		return false;
	}
}

What is important is that the name-tag is the same for all radio buttons that are considered to be part of the same group. This way the document-object will generate array properties in the form-objects for the radio buttons. As we loop through that array we can check if the radio button checked-property is true. If it is, we found the checked radio button.

JavaScript: Basic form validation

This is a follow-up article to a previous article about basic DOM manipulation with JavaScript which you might want to read if you’re new to JavaScript.

The simplest way to get the element from the document object using the getByElementId() method and then checking the value property of the element:

var name = document.getElementById("Name");

This finds the element with the ID Name and put it in the variable name. We can now use the element to validate it. The following code is an example of how to check that the name isn’t empty and that the age is numeric and above 0. If there is an error it wil return false and color the background of the faulty input box red:

index.htm

<!DOCUMENT html>
<html>
	<head>
		<title>Javascript DOM manipulation Example</title>
		<script type="text/javascript" src="demo.js"></script>
	</head>
	<body>
		<h1>Javascript form validation test!</h1>
		<form id="MyForm" onsubmit="return validateForm()">
			<p>Name: <input type="text" id="Name" /></p>
			<p>Age: <input type="text" id="Age" /></p>
			<p><input type="submit" id="Submit" value="Submit"/></p>
		</form>
	</body>
</html>

demo.js

function validateName(name)
{
	if(name == "" || name == null || name === "undefined")
	{
		return false;
	}
	
	//Name must be more than one letter
	if(name.length <= 1)
	{
		return false;
	}
	
	return true;
}

function validateAge(age)
{
	if(age == "" || age == null || age === "undefined")
	{
		return false;
	}
	
	if(isNaN(age))
	{
		return false;
	}
	
	if(parseInt(age) <= 0)
	{
		return false;
	}
	
	return true;
}

function validateForm()
{
	//Check name
	var name = document.getElementById("Name");
	var isNameOk = validateName(name.value);
	console.log(name);
	
	if(isNameOk)
	{
		name.style.background = "#FFFFFF";
	}
	else
	{
		name.style.background = "#FF0000";
	}
	
	//Check age
	var age = document.getElementById("Age");
	var isAgeOk = validateAge(age.value);
	
	if(isAgeOk)
	{
		age.style.background = "#FFFFFF";
	}
	else
	{
		age.style.background = "#FF0000";
	}

	return isNameOk && isAgeOk;				
}

We hook up to the onsubmit event on the form element in HTML and we return the value we get from the validation method validateForm. If we return false the form won’t submit and that’s why we alter the form and color it, so that the user can identify where the errors are. This can be made even better by adding text or something but in this demo we’ll keep it simple.

Try a demo here if you want!

JavaScript: Basic DOM manipulation

JavaScript as a language has a couple of built-in objects ready to use such as Array, Boolean, Date, Function, Math, Number, Object, RegExp and String. Depending on your executing environment you may, however, have more objects pre-defined to work with. Most people use JavaScript on their web sites which means the running environment is a browser and it comes with several useful objects. One of these objects is called document and it is the object that we’ll be looking at in this article.

The document object represents the entire HTML structure of the current page and allows for you to easily search the HTML structure using methods such as getElementById and getElementsByClassName. The name of the methods are quite self explanatory and we’ll be using the getElementById method to manipulate a button. We’ll change its text, its background and the font-weight of it:

 

<!DOCUMENT html>
<html>
	<head>
		<title>Javascript DOM manipulation Example</title>
		<script type="text/javascript">
			function handleClick()
			{
				var button = document.getElementById("MyButton");	
				button.innerHTML = "This value just changed!";		
				button.style.background = "#FFF";					
				button.style.fontWeight = "bold"; 					
			}
		</script>
	</head>
	<body>
		<h1>Javascript Button test!</h1>
		<button id="MyButton" onclick="handleClick()">Click here!</button>
	</body>
</html>

What we do here is that we create a function called HandleClick which we hook up to the onclick event of the button. When the button is clicked the function is executed and in it we fetch the button by using the getElementById method of the document object.
The method will return a reference to the button object which is now open for manipulation. We change the text of the button by utilizing the innerHTML property of the button-object. We can manipulate the CSS of the element by going through the style property of the button which contains all the CSS elements ready to be read or written to. Note, however, that some CSS element are hyphenated and they are changed to camelCasing (i.e. font-weight becomes fontWeight and padding-left becomes paddingLeft).

Click here for an example!

A very basic jquery-plugin

This will be a short entry regarding how to create a very simple jquery plug-in. In this example I’ll create a plug-in which will lock text boxes to numeric input only (which can be useful if you want age input or something of the like).

The first thing you need to do is to create a ‘closure’ of the jQuery object. There are a lot of different libraries for javascript and the dollar sign can collide with these. So, to ensure that this won’t happen you can encapsulate it into a self-calling function, looking something like this:

(function($)
{
});

As we are writing a jQuery plug-in we’ll send the jQuery object as an argument. Without the self-caling it could also be written as:

function foo()
{
}

But then we’d had to call our plug-in our selves before we use it, and we don’t want that.
The plug-in itself will be added inside the encapsulation and it basically looks like this:

(function($)
{
	$.fn.numeric = function()
	{
		return this.each(function(idx, element)
		{
			$(element).bind('keydown', function(e)
			{
 
			});
		});
	}
})(jQuery);

$.fn.numeric = function(){} creates the plug-in. This is what you use on your element later (ex: $(‘.foo’).numeric()) to activate it.
It will loop through all elements it’s connected to and bind a keydown event to that element. Then we bind the keydown to each element it loops though and this is where we add our numeric-check, it looks like this:

...
$(element).bind('keydown', function(e)
{
	//8  = Backspace
	//46 = Delete
	if(e.keyCode == 46 || e.keyCode == 8) 
	{
		//Do nothing
	}
	else 
	{
		//48 = 0
		//...
		//57 = 9
		if(e.keyCode < 47 || e.keyCode > 58)
		{
			e.preventDefault();
		}
	}
});
...

We take in an event object from the keydown event. This object contains a property called keyCode. This property tells us which button it was that the user pressed to fire the event.
We check if the button is 46 (delete) or 8 (backspace) and if it is, we do nothing as these buttons are allowed (we could also have added ‘.’ if we want to allow decimals). Then we check if the key code is between 47 and 58 (0-9 key in the key code map) and if it isn’t, we exit the keydown event. This means that no command is sent to the end client (our input box).

The whole code, with bindings, looks like this:

(function($)
{
	$.fn.numeric = function()
	{
		return this.each(function(idx, element)
		{
		$(element).bind('keydown', function(e)
		{
			//8  = Backspace
			//46 = Delete
			if(e.keyCode == 46 || e.keyCode == 8) 
			{
				//Do nothing
			}
			else 
			{
				//48 = 0
				//...
				//57 = 9
				if(e.keyCode < 47 || e.keyCode > 58)
				{
					e.preventDefault();
				}
			}
		});
		});
	}
 
	$(document).ready(function()
	{
		$('.nummer').numeric();
	});
})(jQuery);

A demo can be found here: http://demo.maffelu.net/jquery/basicplugin.htm