max
max

Reputation: 3716

changing a button text after loading/resetting by bootstrap

I'm trying to create like / unlike buttons using bootstrap3.

Here is my button

<button type="button" id="testBtn" 
class="btn btn-success glyphicon glyphicon-thumbs-up"
data-loading-text=" ... "  onclick="like()" >
4</button>

Here is a simplified version of my JavaScript function without AJAX call:

    function like(){
    var btn = $('#testBtn');
    btn.button('loading');

    var current = parseInt(btn.text()); 
    current++;

    console.log(current);

    btn.button('reset');
    btn.text(current);
   }

Usually this works and button text increments on each click.

However now that I'm using bootstrap, after resetting the button it keeps the old text even though in the console.log(current); I see a new incremented one.

I think because I'm using bootstrap button loading/resetting I have to do something else to change button text.

Upvotes: 2

Views: 4432

Answers (2)

Lumi Lu
Lumi Lu

Reputation: 3305

'btn.text()' is getting data-loading-text value, not '4'. So I updated my answer which created vote up and down for you in FIDDLE

HTML

<button type="button" id="testBtn" class="btn btn-success glyphicon glyphicon-thumbs-up" data-loading-text=" ... ">
    4</button>
<button type="button" id="testBtnDown" class="btn btn-success glyphicon glyphicon-thumbs-down" data-loading-text=" ... ">
    4</button>

JS

$('#testBtn').click(function () {
    var cnt=4;
    var btn = $(this);
    btn.button('loading');
    setTimeout(function () {
        cnt++;
        btn.button('reset');
        btn.text('  ' + cnt);
    }, 1000);
 });

$('#testBtnDown').click(function () {
    var cnt=4;
    var btn = $(this);
    btn.button('loading');
    setTimeout(function () {
        if (cnt > 0) {
            cnt--;
        }
        btn.button('reset');
        btn.text('  ' + cnt);
    }, 1000);
 });

Upvotes: 1

Alberto
Alberto

Reputation: 878

The reason for this is related to that function not being on the global context. You can find more details on this answer here.

Basically, recommendation is to do the binding on Document Ready and not to use onclick for this.

Hope this helps!

Upvotes: 0

Related Questions