Reputation: 191
How do I disable a Bootstrap button after it is clicked using Javascript.
I am using the onclick
event but it doesn't get disabled.
Code:
<div class="panel-heading">
<div class="btn-group pull-right">
<a href="/assign" class="btn btn-success">Assign</a>
<a href="#" class="btn btn-primary" onclick="this.disabled=true">Upload</a>
</div>
</div>
Upvotes: 8
Views: 25443
Reputation: 21
The following solution can be used when an element (e.g. button, or link) is rendered as an A (anchor) tag (e.g. command link-buttons in ASPX pages). (Anchors do not have an (HTML) disable attribute, so cannot simply be disabled by setting that attribute. Slightly confusingly, Bootstrap will make the button appear to be disabled, but in practice another click (or worse still, double-clicks) will cause an on-click or href (where this is actually "javascript:...") to be re-invoked.)
NB: Needs jquery.
Add the script from the jsfiddle reference below, to your master page or individual pages.
Apply the disableafteroneclick class to any button rendered as an anchor (A) where you want to restrict second/double clicks
Optionally, add to the a/button data-disabledtext attribute (this will replace the text on the button after the first click.
NB: The disabled nature of the button will only be removed when the page is re-rendered - so this is mostly used where (for example) a submit button which must be click only once, will move the user to another page.
You'll see I've used the lines:
if ($(this).attr("href")) window.location = $(this).attr("href");
return false;
for the first click (where the invocation is needed) - which might have been replaced with simply:
return true;
...but discovered that this doesn't work for IE <= 8 - and our clients need to provide support for IE8! If you know you won't need that, then you certainly could use the simplified code created by that replacement.
Code is at: https://jsfiddle.net/robertgalesorguk/qbq1n369/4/
Upvotes: 2
Reputation: 7060
$("#buttonid").on("click", function() {
$(this).prop("disabled", true);
});
Upvotes: 16
Reputation: 396
add
$(this).prop("disabled",true);
to you click event function
Upvotes: 4