JQuery Switch Through Twitter Bootstrap Classes

Scenario

I would like the user to be able to switch through Twitter Bootstrap button classes using jQuery when the main part of the button is pressed (for quick).

or

Allow user to select state from dropdown menu.

Regardless of the selected state, the entire btn-group must have the same class of buttons.

Not Running (btn-info), In Progress (btn-warning), Completed (btn-success) and Late (btn-error).

What i wish

Buttons

What am i still

This is my HTML code. This is a standard Bootstrap button group.

<div class="btn-group">
    <button type="button" class="btn btn-warning">Week 7</button>
    <button type="button" class="btn btn-warning dropdown-toggle"
      data-toggle="dropdown" aria-expanded="false">
        <span class="caret"></span>
        <span class="sr-only">Toggle Dropdown</span>
    </button>
    <ul class="dropdown-menu" role="menu">
        <li>
          <a href="#">Not Started</a>
        </li>
        <li>
          <a href="#">In Progress</a>
        </li>
        <li>
          <a href="#">Completed</a>
        </li>
        <li class="divider"></li>
        <li>
          <a href="#">Late</a>
        </li>
    </ul>
</div>

This switches all buttons, not just the button that the button is pressed on.

$('.btn-group').click(function () {
  var classes = ['btn btn-info','btn btn-info','btn btn-success'];
  $('.btn').each(function(){
    this.className = classes[($.inArray(this.className, classes)+1)%classes.length];
  });
});
+4
source share
1 answer

HTML JavaScript:

//// TOGGLE ////
// toggle only if the first part of the button (button:first-child) is clicked
$('button:first-child').click(function () {

    var classes = ['btn btn-info','btn btn-warning','btn btn-success','btn btn-danger'],

        // select new class name first so it isn't changed on every iteration (if you use each)
        oldClass = this.className,
        newClass = classes[($.inArray(oldClass, classes)+1)%classes.length];

    // this method keeps all other classes untouched (e.g. dropdown-toogle)
    $([this, this.nextElementSibling])
        .removeClass(oldClass)
        .addClass(newClass);
});

//// SELECT ////
// add a click listener to every a element
$(".btn-group").each(function () {
    var classes = ['btn-info','btn-warning','btn-success','btn-danger'],
        buttons = $(this).children("button");

    $(this).find("a").each(function (index) {

        $(this).click(function () {

            // use the a elements index to get the right array element
            var newClass = classes[index];

            $(buttons)
                .removeClass(classes.join(' '))
                .addClass(newClass);
        });
    });
});

-: http://jsfiddle.net/b9e3ossu/1/

, :).

+1

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


All Articles