Reputation: 8548
I have a snippet to prevent double clicks on links styled as buttons.
$('.btn').on('click', function(e) {
if( $(this).prop('disabled') == true) {
$(this).attr("href","javascript:void(0);");
}
$(this).prop('disabled',true);
});
My problem is that this code seems to prevent any submit button from submitting a form. Is this an expected behavior from the above code?
Upvotes: 0
Views: 311
Reputation: 11126
It appears that disabling the button prevents the event from bubbling up the DOM and triggering the submit. There are several ways around this, but the easiest would probably be checking if it is a submit button on a form and handling it manually like so:
$('.btn').on('click', function(e) {
var trigger = $(this);
if (trigger.prop('disabled') == true) {
trigger.attr("href", "javascript:void(0);");
}
trigger.prop('disabled', true); // disables form submit event bubbling
if (trigger.is('[type="submit"], .submit')) { // check if submit button
var form = trigger.closest("form, .form"); // find form
if (form.length) { // if form exists
form.submit(); // manually trigger form submit
}
}
});
$("form").on("submit", function() {
alert("submitting...");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form style="border: 2px solid black; padding: 10px 0;">
Form:
<input type="submit" class="btn" />
<button class="submit btn">.submit</button>
</form>
<br/>
<button class="btn">Non-form button.btn</button>
<input type="button" class="btn" value="non-form input.btn">
Upvotes: 1