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

No comments:

Post a Comment