2
<div class="btn-group btn-group-toggle" data-toggle="buttons">
    <label class="btn btn-secondary active">
        <input type="radio" name="options" id="option1" autocomplete="off" 
        checked> Active
    </label>
    <label class="btn btn-secondary">
        <input type="radio" name="options" id="option2" autocomplete="off"> 
        Radio
    </label>
    <label class="btn btn-secondary">
        <input type="radio" name="options" id="option3" autocomplete="off"> 
        Radio
    </label>
</div>

$().button('toggle') : Toggles push state. Gives the button the appearance that it has been activated.

Screenshot of image of RadioButtonList. From the left-most button you can see that it looks like it has been clicked when it is clicked.

enter image description here

Screenshot of the Login-page that I am currently making. When I click on either of the 'radio' buttons their appearance does not changed, so I have to use the method $().button('toggle'), but I do not know where or how to use it.

enter image description here

Naresh
  • 16,698
  • 6
  • 112
  • 113
psychicspies
  • 31
  • 2
  • 5

2 Answers2

1

You just need to add the correct selector to the jQuery function. Try using this instead:

$(".btn-group").button("toggle");

And now your code should work.

Hopefully this helps!

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

I came across this question because I was stumped by a similar use case. It's my first time working with jquery, so I was a little confused by the syntax at first. (tl;dr diff between JS/jquery see 4.)

I wanted to expand on the 1st answer because I would have appreciated someone else doing the same. I was working through this problem on Bootstrap 4.5.3 for a couple hours, completely stumped as to why my radio buttons wouldn't show the toggle effect, before I realized there was a library requirement for the button() method, which I did not see in the docs.

  1. The required library: If you want this feature to work "the bootstrap way", the buttons.js library before invoking the jquery script, which in an npm-installed package is located at node_modules/bootstrap/js/dist/

Load + init example:


    <script src="node_modules/bootstrap/js/dist/buttons.js">
    $('.btn-group').button('toggle');
    </script>

you can disaggregate the jquery and loading the script if that helps you keep things straight (separate <script /> tags for each):


    <script src="node_modules/bootstrap/js/dist/buttons.js"> </script>
    <script>$('.btn-group').button('toggle');</script>

  1. Selecting the proper element for your use case: A slightly more specific way to target the buttons is explained by TWBS in another bootstrap example for tooltips - this is targeting the children of an element by data attribute: https://getbootstrap.com/docs/4.5/components/tooltips/#example-enable-tooltips-everywhere

    $('[data-toggle="button"]').button('toggle');

More about selecting element by data attribute here: Selecting element by data attribute with jQuery

  1. Right target for use case continued: You can attach it to elements in any number of ways, here's an example using the IDs of each button, the # hash symbol denoting an ID selector (the . period symbol denoting a class, just like css) - you simply put them in an array and pass that to the button() method:
    $(['#option1', '#option2', '#option3']).button('toggle');

This could be classes (starting with a period, e.g. ['.button-one', '.button-two'], etc.

  1. Big picture: If you're seeing the pattern here, jquery uses these $(DOM ELEMENT).method(SCOPE) statements, which are a more terse form of the syntax used by JS, which would be a lot more verbose, something like:
    let lis = document.getElementsByTagName('li');
    let firstLi = lis[0];
    firstLi.addEventListener('click', () => console.log('clicked first li'))

So it's basically the same, just way less verbose. Since jquery was developed specifically to handle the DOM, this makes sense.

If you want to achieve the same look without loading the bootstrap buttons.js library, you can attach/remove the .active class, which when attached mutes the appearance of the radio button, to the label of the buttons in question with something like:

    $('.btn').on('click', function () {
    $(this).siblings('label').removeClass('active');
                $(this).addClass('active');
            });

Statement exmplained: When an element with the .btn class is clicked, it will remove all .active classes from any sibling elements with the tag type label, and add the .active class to the one you clicked.

If you examine the button.js library, though, you can see that toggle() does quite a bit more stuff behind the scenes than just applying/removing .active (and has many, many, many conditionals for different possible use cases...):

     _proto.toggle = function toggle() {
          var triggerChangeEvent = true;
          var addAriaPressed = true;
          var rootElement = $__default['default'](this._element).closest(SELECTOR_DATA_TOGGLES)[0];
    
          if (rootElement) {
            var input = this._element.querySelector(SELECTOR_INPUT);
    
            if (input) {
              if (input.type === 'radio') {
                if (input.checked && this._element.classList.contains(CLASS_NAME_ACTIVE)) {
                  triggerChangeEvent = false;
                } else {
                  var activeElement = rootElement.querySelector(SELECTOR_ACTIVE);
    
                  if (activeElement) {
                    $__default['default'](activeElement).removeClass(CLASS_NAME_ACTIVE);
                  }
                }
              }
    
              if (triggerChangeEvent) {
                // if it's not a radio button or checkbox don't add a pointless/invalid checked property to the input
                if (input.type === 'checkbox' || input.type === 'radio') {
                  input.checked = !this._element.classList.contains(CLASS_NAME_ACTIVE);
                }
    
                if (!this.shouldAvoidTriggerChange) {
                  $__default['default'](input).trigger('change');
                }
              }
    
              input.focus();
              addAriaPressed = false;
            }
          }
    
          if (!(this._element.hasAttribute('disabled') || this._element.classList.contains('disabled'))) {
            if (addAriaPressed) {
              this._element.setAttribute('aria-pressed', !this._element.classList.contains(CLASS_NAME_ACTIVE));
            }
    
            if (triggerChangeEvent) {
              $__default['default'](this._element).toggleClass(CLASS_NAME_ACTIVE);
            }
          }
        };

So, probably best just to load button.js...

Side Note: Arrow functions in jquery more often than not wind up targeting the window object, so might be best to avoid unless you know what you're doing.

AveryFreeman
  • 1,061
  • 2
  • 14
  • 23