Reputation: 13975
I have an element inside a div that is "draggable" jquery ui. And I am trying to remove that entire div. My element looks like
<div class="draggable">
<img ...>
<div class="delete">CLICK TO DELETE</div>
</div>
And it has a draggable event on it. And I want it so when you click on the delete button it deletes that entire div. But it does not seem to work. I've tried $(this).parent/parents.remove
and neither of those work, they don't even return any kind of an object (console.log($(this).parent());
returns []).
My delete function looks like
// Delete Image functionality
$('.delete').click(function() {
$this.parent().draggable('disable');
// Post the DELETE request
$.get('delete/', { d: '1' , id:photo }, function(data) {
if (data == "true") {
$(this).parent().remove();
} else {
alert("An error has been encountered, please try again later");
}
});
});
Any idea what's up?
Upvotes: 2
Views: 212
Reputation: 13714
"this" inside of the inner function is different from "this" in the outer scope. Try storing "this" in another variable, and using that variable within the outer function, i.e.:
// Delete Image functionality
$('.delete').click(function() {
$this.parent().draggable('disable');
var that = $(this);
// Post the DELETE request
$.get('delete/', {d:'1',id:photo}, function(data) {
if(data == "true") {
that.parent().remove();
}else{
alert("An error has been encountered, please try again later");
}
});
});
Upvotes: 0
Reputation: 237817
The problem is that, within the callback to $.get
, this
is set to the jqXHR
instance. So you can do, for instance, this.responseText
, should you wish. Obviously it is no longer set to the element.
You need to give the element an alias that isn't overwritten:
$('.delete').click(function() {
var clicked = this;
$this.parent().draggable('disable');
// Post the DELETE request
$.get('delete/', {d:'1',id:photo}, function(data) {
if(data == "true") {
$(clicked).parent().remove();
}else{
alert("An error has been encountered, please try again later");
}
});
});
There are various other ways you could do it: the most efficient would be var parent = $(this).parent().draggable('disable')
(presuming draggable
is chainable, which it probably is). Another option would be to go by the event's currentTarget
property:
$('.delete').click(function(event) {
// ...
$(e.currentTarget).parent().remove();
I think the version I've given is probably the clearest at showing why this didn't work for you, which is why I chose it.
Upvotes: 1