views:

33

answers:

3

Hello,

Somewhat new to jQuery, so excuse the attempt at properly identifying things.

I need an element's id to be reflected in a selector that is a couple functions deep, and I'm not quite sure how to go about doing that.

$("input[type='file'][id^='pic_']").change(       //I need this element's id...
 function()
 {
  $("."+this.id).hide("fast",
   function()
   {
    //..to be reflected in this class selector
    $("."+this.id).attr("checked", true);
   }
  );
 }
);

Thanks for your help in advance. :-)

A: 

Seems like a question of variable scope:

$("#my_input").change(function() {
    var my_id = $(this).attr('id');
    $(this).hide('fast', function() {
        alert(my_id); // Will show an alert with the id from above.
        alert($(this).attr('id')); // *Should* show an alert with the same id.
    });
});
jgeewax
`$(this).id` is invalid - but the idea is correct - `$(this).attr('id')` or `this.id` would be valid options. But I think a closure is definitely the right idea here.
Alex Sexton
using the variable worked great! But I wonder if there is a cleaner way of getting it. Something like this.this.id maybe?
tscully
A: 

The this variable in an event callback is the DOM element hosting the event. In the change function callback, this is the element changed. Therefore:

$("input[type='file'][id^='pic_']").change(
  function() {
    $(this).hide("fast",
      function() {
        $(this).attr("checked", true);
      }
    }
  }
}
Jeff Ober
+1  A: 

This uses closures to bring a variable with the id into the scope of the innermost function.

$("input[type='file'][id^='pic_']").change(       //I need this element's id...
        function()
        {
                var fileSelector = "." + this.id;
                $(fileSelector).hide("fast",
                        function()
                        {
                                //..to be reflected in this class selector
                                $(fileSelector).attr("checked", true);
                        }
                );
        }
);
gWiz
My mistake, I should've been more clear:The element being changed is a file input:$("input[type='file'][id^='pic_']").changeThe element being hidden is a div:$("."+this.id).hideAnd the element being checked is of course a checkbox:$("."+this.id).attr("checked", true);What I want to happen is when a user puts a file into the file input, the checkbox and it's label (inside the div) get hidden, and then the checkbox gets checked.
tscully
Oh, well it looks like your original code sample should work fine. Does it not?
gWiz
Unfortunately no, since $("."+this.id).attr("checked", true); is being called by a function from $("."+this.id).hide, it returns that element's id and not the element selected by $("input[type='file'][id^='pic_']").change, and they are different.
tscully
I see, I've updated my answer in response.
gWiz
Thanks for your help!
tscully