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?
HTML
<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>
<label class="btn btn-default btn-xs">
<input type="radio" name="display_share_btn" value="false">OFF
</label>
</div>
Javascript
$(document).on('click','.sp_toggle_switch label.active',function(){
$(this).siblings('label:not(.active)').trigger('click');
});
CSS
.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 label.active {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 label.active {width: 32px; }
3
Answers
Simply add "return false" after the JS click and it will stop further JS from executing.
Here is an updated fiddle
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:
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.
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