How to Easily Loop Through Form Elements

A couple of days I was working on a script where I needed to loop through all the values of an undefined number of input fields. This number was undefined because the user could add and remove fields, to accomplish this I made use of JQuery’s $.each function like this.

Let’s say you have several input fields of type “text” with class “items”

<input type="text" class="items" /><br />
<input type="text" class="items" /><br />
<input type="text" class="items" /><br />
<input type="text" class="items" /><br />
<input type="text" class="items" /><br />
<input type="text" class="items" /><br />
<input type="text" class="items" /><br />
<input type="text" class="items" /><br />
<input type="text" class="items" /><br />
<input type="text" class="items" /><br />

and you want to loop through the values of these fields when the user performs a certain action, let’s say he/she clicks a button.

<button>Get Values</button>

Then the resulting javascript code would be the following

	$("button").click(function(){
	// when the button is clicked
		$.each($(".items"),function(i,e){
		// loop through all the items
			// and alert the value
			alert(e.value);
		});
	});

With this code am able to loop through all the items and get their value inside the loop with e.value . The $.each loop is great for user made AJAX forms, lists and shopping carts where you have an undefined number of elements.