Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use jQuery get the ID of the div which has been clicked on?

Tags:

jquery

I need to get the ID of the clicked-on div.

Now when I click on status class I an returned undefined id.

Here is my javascript code

jQuery(document).ready(function() {
    $(".status").bind('click', $.proxy(function() {
        var status = $(this).attr('id');
        alert(status);
    }, this));
});​

and HTML

<div class="status" id="s_1">111111</div>
<div class="status" id="s_3">33333</div>
<div class="status" id="s_2">222222</div>

How should I get the correct id value?

like image 998
meli medo Avatar asked Jun 28 '12 16:06

meli medo


People also ask

How do I get the ID of clicked element?

To get the clicked element, use target property on the event object. Use the id property on the event. target object to get an ID of the clicked element.

How can I get the ID of an element using jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

What is div id in JavaScript?

The <div> tag defines a division or a section in an HTML document. The <div> tag is used as a container for HTML elements - which is then styled with CSS or manipulated with JavaScript. The <div> tag is easily styled by using the class or id attribute.

Can div be clicked?

A div is a content division element and is not clickable by default. We may have to use the onclick event handler to process the events emitted by the element when a user clicks on it. The onclick event handler accepts a function or a JavaScript expression preceding the function.


2 Answers

I'm not sure why you're using $.proxy. Removing it should get you the desired results.

$('.status').click(function(event) {
    var status = $(this).attr('id');
});

If you still want to use proxy you can access the clicked element through event.currentTarget

$(".status").bind('click', $.proxy(function(event) {
    var status = $(event.currentTarget).attr('id');
    alert(status);
}, this));
like image 165
digitaldreamer Avatar answered Oct 22 '22 11:10

digitaldreamer


How about:

$('div').on('click', function(){
    alert($(this).attr("id"));
});

Does this have to work only for divs with class status? If so, try:

$('div.status').on('click', function(){
    alert($(this).attr("id"));
});
like image 36
woemler Avatar answered Oct 22 '22 12:10

woemler