views:

58

answers:

4

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

+6  A: 

Try $(this).parent().attr('id');

Keeper
+1  A: 

Change it to the following

$(document).ready(function() {
      $(".common input").click(function() {

        var divId =  $(this).parent().attr('id'));
        alert(divId);
});
mohang
+1  A: 
$(document).ready(function() {
    $(".common input").click(function() {
        alert( $(this).parent().attr('id') ); // <- Use $(this).parent()
    }); // <- don't forget to close this function too
});
Justin Johnson
+1  A: 

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);
         }
     });
});
Tim Down