Reputation: 6587
I have a problem with the jQuery's live() function.
I'm creating the shopping basket with PHP and make a json call to the php script to add specific item to the basket. Rather than re-binding the click to the button ( tag) I've decided to use live(), however it doesn't seem to like it.
Here's my call:
if ($('.add_to_basket').length > 0) {
$('.add_to_basket').live('click', function() {
var button = $(this);
var id = $(this).attr("rel");
$.getJSON("/basket/action/add/id/" + id, function(data) {
if (!data.error) {
$('.basket_no_of_items').text(data.no_of_items);
$('.basket_items_total').text(data.total);
button.text('Remove from the basket');
}
});
return false;
});
}
Any idea what I might be doing wrong?
I've checked with firebug and it seem to post the request to only /basket/action/add - without id bit.
Upvotes: 1
Views: 705
Reputation: 3257
change $.getJSON("/basket/action/add/id/" + id, function(data) {})
to $.getJSON("/basket/action/add/id/" ,{ pid : id}, function(data) {})
Upvotes: 1
Reputation: 550
The whole idea of using live()
is to register a function on the occurrence of an event (eg. click) on a set of elements whether they exist or not at the time of creation of the function.
Adding ($('.add_to_basket').length > 0)
will check whether this particular set of elements exist or not. This is counter productive as per my description above. So, either:
($('.add_to_basket').length > 0)
and this should work for all .add_to_basket
elements$('.add_to_basket').live('click', function() {...});
to $('.add_to_basket').click(function() {...});
and wrap it around with a $(document).ready()
to ensure that all DOM elements have loaded when the function is registered to the click.Hope this makes sense.
Sumit
Upvotes: 4
Reputation: 4583
Try removing the "length" check, I bet it's interfering with the .live() function.
Upvotes: 1