Let's say I have this HTML...
<button class="btn-remove-this">Remove this</button>
<button class="btn-remove-that">Remove that</button>
<button class="btn-remove-some-other-thing">Remove some other thing</button>
<!-- and many more 'Remove ...' buttons -->
...and this JavaScript.
$(function() {
$('.btn-remove-this').click(function() {
functionWhichRemovesThis();
}
$('.btn-remove-that').click(function() {
functionWhichRemovesThat();
}
$('.btn-remove-some-other-thing').click(function() {
functionWhichRemovesSomeOtherThing();
}
// and many more click handlers
});
Now I would like to prompt the user with a confirm dialogue before removing all those things. Is there a way to do it without adding and calling confirm
inside every single click handler?
I have on my mind something like adding a single class to all of the different buttons (let's say btn-remove
) and then adding a single click handler which could look like this:
$('.btn-remove').click(function() {
if (confirm('Are you sure you want to remove this?')) {
// execute the body of the "more specific" click handler
} else {
// prevent the body of the "more specific" click handler from executing
}
}
You may write different click handler for different button and call common check function will function you want to call has a parameter and on ok click you can call that callback function.
$('.btn-remove-this').click(function() {
check(functionWhichRemovesThis);
});
$('.btn-remove-that').click(function() {
check(functionWhichRemovesThat);
});
$('.btn-remove-some-other-thing').click(function() {
check(functionWhichRemovesSomeOtherThing);
});
function check(callback){
if (confirm('Are you sure you want to remove this?')) {
callback();
} else {
// prevent the body of the "more specific" click handler from executing
}
}
This is also a way. So that you dont have to modify your code much.
I suggest you to use data-*
for it here in your case:
<button class="btn-remove" data-func="functionWhichRemovesThis">Remove this</button>
<button class="btn-remove" data-func="functionWhichRemovesThat">Remove that</button>
<button class="btn-remove" data-func="functionWhichRemovesSomeOtherThing">Remove some other thing</button>
Now in your js code you can do this:
var removeUtil = {
functionWhichRemovesThis : function(){},
functionWhichRemovesThat : function(){},
functionWhichRemovesSomeOtherThing : function(){}
};
$('.btn-remove').click(function() {
if (confirm('Are you sure you want to remove this?')) {
var removeIt = $(this).data('func');
removeUtil[removeIt];
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With