jQuery: Store ID of all TextBoxes into an Array

I was storing the ID attribute of all the textboxes on a page, into an array. Although your first response to solve a similar requirement would be to use the $().each() but there is a better way, using map(). Let me show you how.

Declare the following HTML

image
Now in the <head> section, write the following code:
<head>
<title>Read ID attribute (from DevCurry.com)</title>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.5.2.min.js">
</script>

<script type="text/javascript">
$(function () {
 var ids = $("input[type=text]")
  .map(function () {
   return this.id; 
  }).get();
  alert(ids);
});
</script>
</head>

The .map() method is useful for getting/setting the value of a collection of elements, in our case the id attribute of all textboxes. this.id refers to the id attribute of the current DOM element for each iteration.

OUTPUT

image
See a Live Demo

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: