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

LVL 16
hankknightAsked:
Who is Participating?
 
leakim971Connect With a Mentor PluritechnicianCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.