简体   繁体   中英

How to change button in twitter bootstrap using jquery

I have a button:

<button
    class="btn btn-animated btn-default ban-user-btn"
    id="btn-ban-username" // the username is generated by twig
    data-nick="username"  // the username is generated by twig
    data-toggle="modal"
    data-target="#statusModal"
    >
    Ban user
    <i class="fa fa-ban"></i>
</button>

I need to change the button class from "btn-default ban-user-btn" to "btn-success unlock-user-btn". When I do following in my javascript:

var button = $('#btn-ban-username);
button.addClass("btn-default");
button.addClass("ban-user-btn");
button.removeClass("btn-success");
button.removeClass("unlock-user-btn");
button.attr('id', 'btn-unlock-'+nick);
button.html("Unlock user <i class='fa fa-check'></i>");

I get the following:

<button
    class="btn btn-animated btn-default ban-user-btn"
    id="btn-unlock-username"
    data-nick="username"
    data-toggle="modal"
    data-target="#statusModal"
>
    Unlock user
    <i class="fa fa-check"></i>
</button>

As you can see, the ID changes and the button content changes. The classes however do not.

Some ideas?

Cheers

You're adding classes that the button has and removing classes that the button doesn't have.

Try this:

$("#btn-ban-username")
.addClass("btn-success unlock-user-btn")
.removeClass("btn-default ban-user-btn");

In your JavaScript code you have to reverse the order of your addClass and removeClass. addclass function is used to add class to your html control and removeclass for removing class from an html contol.

You have to do this

 var button = $('#btn-ban-username');
        button.removeClass("btn-default");
        button.removeClass("ban-user-btn");
        button.addClass("btn-success");
        button.addClass("unlock-user-btn");
        button.attr('id', 'btn-unlock-dev');
        button.html("Unlock user <i class='fa fa-check'></i>");

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