I have an anchor tag (namely Cancel button) with a class attribute and href attribute in a jsp file .
I have written an onclick
event for the class attribute in a seperate js file. So when the button is clicked, the onclick event executes and then takes to the href link.
When the button is clicked more than once it takes me to an empty page or an error page.
I want to prevent more than one click on the button.
I have tried using event.preventdefault()
function inside my onclick()
function but the href link is not working if I do that.
Any other way?
My JS code:
$('.cancel-btn').on('click',function(evt){
//evt.preventDefault();
//My Code
});
How could you prevent a click on an anchor from going to the link? To prevent an anchor from visiting the specified href, you can call the Event interface's preventDefault() method on the anchor's click handle.
Just use "#/" instead of "#" and the page won't jump. Save this answer.
Using onclick Event: The onclick event attribute works when the user click on the button. When mouse clicked on the button then the button acts like a link and redirect page into the given location. Using button tag inside <a> tag: This method create a button inside anchor tag.
As you mentioned the event is written on that class
, you can use this simple code to ensure that its clicked only once:
$('.cancel-btn').on('click', function(evt) {
// execue your code
$(this).removeClass('cancel-btn');
});
This code will remove the class from the DOM and hence the click
event will never get fired.
Optionally, You can use off()
to remove an event like so:
$(".cancel-button").off("click");
This will remove all click events bound to this element. In your code, it would be like:
$('.cancel-btn').on('click', function(evt) {
// execue your code
$(this).off("click");
});
jQuery one()
method will perform click event only once:
$('.cancel-btn').one('click',function(evt){
// evt.preventDefault();
// code here
});
Also possible using jQuery on()
method that may be more useful when the event should be removed conditionally:
let count = 0; // or may be a boolean flag
$('.cancel-btn').on('click', function(evt){
if (count == 0) {
count++;
// code here
} else {
return false;
// or evt.preventDefault();
}
});
Or like this:
$('.cancel-btn').on('click', function(evt) {
// code here
// then remove the event handler.
$(this).off('click');
});
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