max max - 3 months ago 20
Javascript Question

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.

Answer

'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);
 });
Comments