2

i have this links:

<a id = "link_1" href = "#">Cars</a>
<a id = "link_2" href = "#">Colors</a>
<a id = "link_3" href = "#">Users</a>
<a id = "link_4" href = "#">News</a>

how to get the ID numbers on which I click? For examples i push on link Cars, and i wish get 1, push on Users, get number 3.

Thanks

6 Answers 6

9

This will do:

$('a').click(function(){
  alert(this.id.split("_")[1]);
});
4
  • Thanks, but I allways get: "undefined"
    – lolalola
    Commented Sep 18, 2010 at 18:45
  • @lolalola - Here's an example of Gert's answer using your HTML. jsfiddle.net/QpyVY Did you change something in your code from your question?
    – user113716
    Commented Sep 18, 2010 at 18:53
  • Now, i understand. I must id put in a tag, not on <div>. Thanks ;)
    – lolalola
    Commented Sep 18, 2010 at 18:56
  • @lolalola - Yes, inside of a jQuery event handler, this will refer to the element to which the handler was attached (specifically, the one that received the event). You can place the ID on a <div> if you'd like, but you'll just need to adjust your code as needed. :o)
    – user113716
    Commented Sep 18, 2010 at 19:04
1
$("a").click(function(event) {
    event.preventDefault();
    var theid = $(this).attr("id").split("_");
    theid = theid[1]; //here is the number
}
1
$(function() {
  $('a').click(function() {
     var id = $(this).attr('id');
     alert(id.match(/\d+/)[0];
  });
});
0

Apply a class to all of them to allow for easier manipulation.

This works as described:

<a id="link_1" class="get_id" href="#">Cars</a>
<a id="link_2" class="get_id" href="#">Colors</a>
<a id="link_3" class="get_id" href="#">Users</a>
<a id="link_4" class="get_id" href="#">News</a>

<script type="text/javascript">

    jQuery(document).ready(function() {
        $('.get_id').click(function () {
            if ($(this).attr('id').match('^link_([0-9]+)$'))
            {
                id_num = RegExp.$1;
                alert(id_num);
            }

        });

    });

</script>
0

besser use the html data attribute: data-id="1";

$(document).ready(function() {
  $('#links').find('a').each(function() {
    $(this).click(function() { alert($(this).attr('data-id')); return false; })
  })
})

full code : http://jsbin.com/eyona4/

0
$("a").click(function () {
    var theIdNum = parseInt(this.id.replace(/\D/g, ''), 10);
});

honestly I don't know if that will even work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.