skip to Main Content

I basically created an on/off switch using twitter bootstrap’s Button Group component using two radio buttons.

The problem is when I click an “active” (or “checked”) radio button I want the switch to trigger a change anyway. I can do this via Javascript, but for some reason it automatically clicks back after my JS completes.

So essentially I click, my JS clicks the other label, then Bootsrap clicks it back. Anyway to overwrite Bootstraps behavior?

Here is a fiddle


<div class="btn-group sp_toggle_switch" data-toggle="buttons">
    <label class="btn btn-primary btn-xs">
        <input type="radio" name="display_share_btn" value="true">ON
    <label class="btn btn-default btn-xs">
        <input type="radio" name="display_share_btn" value="false">OFF




.sp_toggle_switch label:not(.active ) {background:#ffffff;  border-color: #ccc;}
.sp_toggle_switch label:not(.active ):hover {background:#f1f1f1;}
.sp_toggle_switch label {text-indent: 99px; overflow: hidden; width: 30px;}
.sp_toggle_switch {text-indent: 0px; width: 36px;}
.sp_toggle_switch.switch_sm label {width: 24px; height: 17px; font-size: 10px; line-height: 14px;}
.sp_toggle_switch.switch_sm {width: 32px; }



  1. Chosen as BEST ANSWER

    Simply add "return false" after the JS click and it will stop further JS from executing.

        return false;

    Here is an updated fiddle

  2. So if I understand correctly, you want the switch to toggle regardless of where it’s clicked? If so, this is kind of lazy, but will probably work:

        var inactive = $(this).siblings('label').not('.active');
        setTimeout(function() {
        }, 100);

    I know it doesn’t answer your question about disabling the default behavior, but I’m not sure it’s wise to mess with that, anyway. This gets you what I think you want in a way that’s most likely seamless to the user, though admittedly, a little ugly.

    Login or Signup to reply.
  3. Wow…I was determined to figure this one out for some reason. I worked on it a bit yesterday with no luck, but I think I mastered it this morning. I have it working in my environment, so hopefully it works for you

    $('.sp_toggle_switch label').on('click',function(e){
        var parent = $(this).closest('[data-toggle="buttons"]');
        if ( $(this).hasClass('active') ) {
            parent.find('label').not('.active').find('input:radio').attr('checked', 'checked');
            e.preventDefault(); // to prevent bootstrap from triggering after class change
            return false;
        } else {
            $(this).find('input:radio').attr('checked', 'checked');
            return true;
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top