JQuery attr () does not work on Bootstrap button after reset

I have a very simple code that does not work, and I do not understand what I am missing.

External resources

<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script> 

HTML

 <p> <button id="btn-id" class="btn btn-large btn-primary" type="button" data-loading-text="loading stuff...">Click Me</button> </p> 

Javascript

 $(document).ready(function () { $("#btn-id").button(); $("#btn-id").click(function () { //$("#btn-id").attr("disabled",true); $(this).button('loading'); setTimeout(function () { //this desn't work. The button resets but it doesn't get disabled afterwards $("#btn-id").button('reset').attr("disabled", true); //the bellow line works as expected //$("#btn-id").button('reset').addClass("btn-success"); }, 2000); }); }); 

It seems like after button('reset') I can addClass('someclass') , but I can no longer disable this button.

Why is this not working and how can I fix it?

jsFiddle

+6
source share
4 answers

Not sure if this is the right way, but you can use a workaround

 $(document).ready(function () { $("#btn-id").button(); $("#btn-id").click(function () { $(this).button('loading'); setTimeout(function () { $("#btn-id").addClass('btn-success').data('loading-text', 'OK').button('loading') }, 2000); }); }); 

Fiddle

+2
source

You must add the 'disabled' class on top of the disabled attribute (it works the same in bootstrap 3):

 $("#btn-id").addClass('btn-success').attr('disabled', 'disabled').addClass('disabled').html('OK'); 

jsFiddle

+1
source

The problem is that setTimeout is used in the Button.prototype.setState () method:

https://github.com/twitter/bootstrap/blob/master/js/bootstrap-button.js#L46

The following is a workaround:

 var $btn = $('.btn-save'); $btn.button('reset'); setTimetout(function() { $btn.attr('disabled', 'disabled'); // Disables the button correctly. }, 0); 

(Fiddle: http://jsfiddle.net/f0t0n/BKXVA/ )


Source: https://github.com/twbs/bootstrap/issues/6242
Credit: https://github.com/f0t0n

+1
source

Use .prop() instead of .attr()

Updated Code

 $(document).ready(function () { $("#btn-id").button(); $("#btn-id").click(function () { $("#btn-id").prop("disabled",true); $(this).button('loading'); setTimeout(function () { //this desn't work. The button resets but it doesn't get disabled afterwards $("#btn-id").button('reset').prop("disabled", true); //the bellow line works as expected //$("#btn-id").button('reset').addClass("btn-success"); }, 2000); }); }); 

jsFiddle demo

0
source

Source: https://habr.com/ru/post/950710/


All Articles