• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 282
  • Last Modified:

jQuery: Return number of item clicked on by class

I have four items with a class of xyz.

When you click on one of the items, I want the number of that item to be returned.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<style type="text/css">
a {display: block; text-decoration: underline; color: blue; cursor: pointer;}
</style>

</head>
<body>

     <p>
      <a class="xyz">Click Here (Should alert "1")</a>
     </p>
     <p>
      <a class="xyz">Click Here (Should alert "2")</a>
     </p>
     <p>
      <a class="xyz">Click Here (Should alert "3")</a>
     </p>
     <p>
      <a class="xyz">Click Here (Should alert "4")</a>
     </p>


<script type="text/javascript">
/*<![CDATA[*/

$('.xyz').click(function() {

alert( 'I want the number of the item clicked on.  If the third item with a class of "xyz" was clicked on the number to alert should be 3' );

});

/*]]>*/
</script>

</body>
</html>

Open in new window

0
hankknight
Asked:
hankknight
  • 2
1 Solution
 
leakim971PluritechnicianCommented:
Use index : http://api.jquery.com/index/


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<style type="text/css">
a {display: block; text-decoration: underline; color: blue; cursor: pointer;}
</style>

</head>
<body>

     <p>
      <a class="xyz">Click Here (Should alert "1")</a>
     </p>
     <p>
      <a class="xyz">Click Here (Should alert "2")</a>
     </p>
     <p>
      <a class="xyz">Click Here (Should alert "3")</a>
     </p>
     <p>
      <a class="xyz">Click Here (Should alert "4")</a>
     </p>


<script type="text/javascript">
/*<![CDATA[*/

$('.xyz').click(function() {

var position = $(this).index('.xyz') + 1;

alert( position );

});

/*]]>*/
</script>

</body>
</html>

Open in new window

0
 
leakim971PluritechnicianCommented:
Thanks for the points!
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now