jQuery .each() which better than for loop

Want to introduce jQuery .each() method, which is very useful method when you handle array of objects.

For example, we have 4 dispatch fields in the form, and we don’t want dispatch time is in the future, so we have to create validation check on these fields. In the old way, we have use check each fields, but then I found we can use jQuery .each() which much easier to get the work done.

var initial_dispatch_request = $("#entry_initial_dispatch_request");
var first_tech_on_site = $('#entry_first_tech_on_site');
var second_dispatch_request = $("#entry_second_dispatch_request");
var second_tech_on_site = $('#entry_second_tech_on_site');
var items = [initial_dispatch_request, first_tech_on_site, second_dispatch_request, second_tech_on_site];
	if(compareDate(item.val(), 'now') == 1)
		alert('Dispatch datetime fields cannot be in the future!');
		return false;
	} else {

Please note: above compareDate is the function which compare two given date. like below.

* compare two datetime string
function compareDate(date1,date2)
	var date_1 = new Date(date1);
		var date_2 = new Date();
	} else {
		var date_2 = new Date(date2);
	if(date_1 > date_2)
		return 1; //date1 > date2
	} else {
		return 2; //date1 <= date2

About qianggan

Sr. Software Engineer
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s