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?
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.
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.
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.
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.
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));
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"));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With