Jquery click once then disable / enable element
I have many lines
- List item - delete
- List item - delete
- List item - delete
as above 3 lines .. it removes the link, on click I want to disable this link until I get a response from ajax saying ok, delete it or not is not ok, do not delete it, user is not the owner, then I have to return the item back to clicks .. if it makes sense
basically prevents the item from being clicked and then restores the item on error from the backend.
what methods do i need to use for this? im using live method if i use die then how can i restore again?
source to share
As requested, here's a version that uses links instead of buttons.
<ol>
<li id="item-1">List item <a href="delete.php?1">Delete</a></li>
<li id="item-2">List item <a href="delete.php?2">Delete</a></li>
<li id="item-3">List item <a href="delete.php?3">Delete</a></li>
</ol>
And JS support for that would be
$("ol").click(function(evt){
if (evt.target.nodeName != "A") {
return true;// it not the delete link, so we don't have to do anything
}
var listItem = $(evt.target.parentNode);
if (listItem.hasClass("disabled")) {
return true;// we're still processing this already deleted list item
}
listItem.addClass("disabled");// lock the list item (perhaps visually too)
// set up the AJAX call
$.post("evaluator.php", {listId : listItem.attr("id")}, function(data){
// let suppose that we get "1" if the user can perform the procedure
if (data == "1") {
// request approved, remove the list item
listItem.fadeOut("fast", function(){
$(this).remove();
});
} else {
// release the lock
listItem.removeClass("disabled");
// request denied, rollback
alert("Sorry, you can't do that.");
}
});
// here we stop the click event, so the URL in href won't be called.
// you can "disable" a link by returning false on a click event
// e.g. <a href="url" onclick="return false">disabled link</a>
return false;
});
source to share
The best way would be to create a separate function to handle the AJAX call so you can do
$(".delete").bind("click", deleteItem);
And in your deleteItem function, you can undo this by doing
function deleteItem(delBtn) {
$(delBtn).unbind("click", deleteItem);
//ajax call
onerror: function() {
$(delBtn).bind("click", deleteItem);
}
}
edit: Implemented what you are using live
, which is another version bind
. So in the above example, you can just switch the keyword bind
for live
and unbind
for die
. And he should do the same (:
source to share