I have a form that sends an email upon clicking a button. However, while the email is being sent, the button remains active, allowing users to click it multiple times, which interrupts the email-sending process. I want to add a ‘disabled’ class to the button as soon as it’s clicked. I attempted to achieve this with the following code, but it doesn’t work.
Please assist me with this problem.I tried the following codes
<div class="d-grid mt-3">
<button class="btn btn-primary" type="submit" name="authoriseUser" id="authoriseUser" onclick="disableBTN()">Enroll New Admin <i class="fas fa-sign-in-alt ms-1"></i></button>
</div>
// JS & Jquery Code that I Tried are in the following order
// First Attempt - didn't work
<script type="text/javascript">
$(document).ready(function(){
$("#authoriseUser").on('click',function(){
$(this).removeClass('btn btn-primary')
$(this).addClass('btn btn-primary disabled')
});
});
</script>
//Second Attenpt - didn't Work
<script type="text/javascript">
$(document).ready(function(){
$("#authoriseUser").on('click',function(){
$(this).removeClass('btn btn-primary').addClass('btn btn-primary disabled');
});
});
</script>
//Third Attempt - Didn't Work
<script type="text/javascript">
$(document).ready(function(){
$("#authoriseUser").on('click', function(){
$(this).addClass('disabled').attr('disabled', true);
});
});
</script>
3
Answers
Instead of removing the ‘btn btn-primary’ classes, you can simply add the ‘disabled’ class.
So, when the button is clicked, the ‘disabled’ class will be added to it + the button disabled and there’s no need to add ‘btn-primary’ again.
you can use like this:
It is generally not a good idea to use inline event handlers.
Without jQuery and using event delegation disabling/enabling a button after click is as easy as: