Reputation: 78991
My HTML is something like this
<div id="mydiv" class="common">
<input type="text" id="text1" value="" />
<input type="text" id="text2" value="" />
</div>
I am assigning a function on the onclick event of the textbox like this
$(document).ready(function() {
$(".common input").click(function() {
//////// What I am trying to do is access the id of its parent
// in this case it is "mydiv"
alert($(this:parent).attr('id'));
});
But it is not working
Upvotes: 1
Views: 267
Reputation: 324567
You'd be better off using event delegation and only having one event handler on the parent <div>
. This will be more efficient by reducing the number of event handlers required, and by replacing the descendant and element selector with the much simpler and faster ID selector. Also, within the event handler function you automatically have references to both elements you're interested in (via evt.target
and this
) without having to do any traversal.
$(document).ready(function() {
$("#mydiv").click(function(evt) {
if (evt.target.tagName.toLowerCase() == "input") {
alert("Clicked input with ID " + evt.target.id);
alert("Parent ID: " + this.id);
}
});
});
Upvotes: 2
Reputation: 31300
$(document).ready(function() {
$(".common input").click(function() {
alert( $(this).parent().attr('id') ); // <- Use $(this).parent()
}); // <- don't forget to close this function too
});
Upvotes: 1
Reputation: 2921
Change it to the following
$(document).ready(function() {
$(".common input").click(function() {
var divId = $(this).parent().attr('id'));
alert(divId);
});
Upvotes: 1