简体   繁体   中英

How to disable bootstrap button after one click using javascript

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>
$("#buttonid").on("click", function() {
    $(this).prop("disabled", true);
});

add

$(this).prop("disabled",true);

to you click event function

The following solution can be used when an element (eg button, or link) is rendered as an A (anchor) tag (eg 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.

  1. Add the script from the jsfiddle reference below, to your master page or individual pages.

  2. Apply the disableafteroneclick class to any button rendered as an anchor (A) where you want to restrict second/double clicks

  3. 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM