Reputation: 7138
I have this code:
success:function(data){
newAttrValue = $('.addwish').attr('data-tooltip').closest().replace("Add to wishlist", data);
$('.addwish').attr('data-tooltip', newAttrValue);
}
and it returns:
TypeError: $(...).attr(...).closest is not a function
While if I use:
success:function(data){
newAttrValue = $('.addwish').attr('data-tooltip').replace("Add to wishlist", data);
$('.addwish').attr('data-tooltip', newAttrValue);
}
without .closest()
it works fine.
The reason that I want use closest it to avoid changing all my items tooltip and only change tooltip of action item.
<a data-prodid="{{$cross->id}}" data-userid="{{Auth::user()->id}}" href="#" class="tt-btn-wishlist addwish" data-tooltip="Add to WishList" data-tposition="left"></a>
Any idea?
full JavaScript code
$(document).ready(function(){
$('.addwish').on('click', function(e){
var productID = $(this).data('prodid');
var userID = $(this).data('userid');
e.preventDefault();
$.ajax({url:"{{ url('wishlist') }}",
type:"POST",
dataType:"json",
data:{
"_token": "{{ csrf_token() }}",
"product_id": productID,
"user_id": userID,
},
success:function(data){
alert(data);
}
});
});
});
Upvotes: 0
Views: 80
Reputation: 21672
You're getting that error because .attr('data-tooltip')
returns a string. Strings don't have a .closest()
method.
You can use $(this)
to refer to the clicked element. If you want to replace the entire tooltip, no need to use .replace()
- just overwrite the data-tooltip
entirely:
$('.addwish').on('click', function(e){
var $self = $(this); //This allows us to use $self as the target element
$.ajax({
//...
success: function(data) {
$self.attr("data-tooltip", data);
}
//...
});
});
Upvotes: 1