Utilizing tagsinput in conjunction with bootstrap4, my goal is for the user to be able to delete a tag by clicking on the 'x' button. Upon deletion, an ajax request is sent to the server to verify if the user has permission. The server will respond with either yes or no (and proceed to delete the tag from the database if allowed). Subsequently, tagsinput should be notified to remove the tag from both the input element and its internal state on the client side.
To achieve this, I have incorporated the beforeItemRemove
event into the tagsinput-element and utilized event.cancel=true;
to prevent tag deletion. Here's how:
$(inputel).on('beforeItemRemove', function(event) {
ajaxreq(..., onSuccess(r){}, onError(e,m){ event.cancel = true; });
});
Unfortunately, setting event.cancel
comes too late as the event wraps up before the completion of the ajax request!
Hence, what I ultimately resorted to was:
event.cancel = true; // cancellation of deletion by default
$(inputel).on('beforeItemRemove', function(event) {
ajaxreq(..., onSuccess(r){
// If ajax succeeds and the server permits deletion, we also remove it from inputel
$(inputel).tagsinput('remove', event.item, {preventPost: true});
}, onError(e,m){});
});
// The event fires much earlier than the ajax request completes,
// but with event.cancel=true, it remains inactive until triggered by 'remove'
Is this solution correct?
UPDATE: For further reference, please visit: (search for beforeItemRemove
)
ANOTHER UPDATE: After testing, I can confirm that this method works when a user is denied permission to delete a tag, preventing any changes within the input field. However, in scenarios where deletion is permitted and executed, the event triggers repeatedly (despite preventPost: true
, which presumably removes without triggering the removal event) and causes issues in the database.