64

I have a Twitter Bootstrap buttons-radio and hook an onclick event to it. But how do I check which of the buttons that got triggered?

My first thought was to simply check for the class 'active', but this should create a race condition (result depends on whether the Twitter Bootstrap event or my own onclick event is handled first).

9 Answers 9

77

This is a really annoying one. What I ended up using is this:

First, create a group of simple buttons with no data-toggle attribute.

<div id="selector" class="btn-group">
    <button type="button" class="btn active">Day</button>
    <button type="button" class="btn">Week</button>
    <button type="button" class="btn">Month</button>
    <button type="button" class="btn">Year</button>
</div>

Next, write an event handler that simulates the radio button effect by 'activating' the clicked one and 'deactivating' all other buttons. (EDIT: Integrated Nick's cleaner version from the comments.)

$('#selector button').click(function() {
    $(this).addClass('active').siblings().removeClass('active');

    // TODO: insert whatever you want to do with $(this) here
});
8
  • 26
    A slightly concise and optimized (no double call to selector) version: $(this).addClass('active').siblings().removeClass('active');
    – Nick
    Feb 16, 2014 at 2:14
  • this doesn't work with radio button. how to specify which one is which if each radio button does different thing Aug 9, 2014 at 2:54
  • @MurhafSousli I'm not sure I understand your problem. If you insert your code where I put the // TODO, you should be able to access the freshly selected radio button as $(this). Aug 9, 2014 at 9:18
  • @Nick I really like your solution, so I decided to integrate it into the answer, to give it a bit more spotlight. Hope you don't mind! Aug 9, 2014 at 9:22
  • Improvement: It is better to use mousedown event, because the colors of the buttons change on mousedown (incomplete click). Jun 23, 2016 at 13:26
77

I see a lot of complicated answers, while this is super simple in Bootstrap 3:

Step 1: Use the official example code to create your radio button group, and give the container an id:

<div id="myButtons" class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option3" autocomplete="off"> Radio 3
  </label>
</div>

Step 2: Use this jQuery handler:

$("#myButtons :input").change(function() {
    console.log(this); // points to the clicked input button
});

Try the fiddle demo

5
  • 3
    This is the best solution I agree.
    – Codemole
    Sep 10, 2015 at 7:00
  • @bonez I've added a fiddle, please elaborate why it doesn't work for you. Dec 23, 2015 at 9:41
  • Came across this whilst looking for the solution, in this instance have your fiddle look for the checked condition of the put console.log($(this).is(':checked')); into the function and watch the results. Now click on the pre selected check - it returns false every time. Now check another button - oh look, true, now click the same button again - back to false. So not really an ideal solution. Jun 23, 2016 at 13:01
  • On my latest Chrome, this works fine. Here's an updated fiddle that I used to test this: jsfiddle.net/9k8oc5pf/109. In what browser does this fail? Jun 27, 2016 at 7:29
  • @SgtOddball The problem you noticed was fixed a few years back, github.com/twbs/bootstrap/pull/11376 (the fiddle is still using 3.0.0, sorry) Sep 27, 2017 at 14:24
23

I would use a change event not a click like this:

$('input[name="name-of-radio-group"]').change( function() {
  alert($(this).val())
})
3
  • 5
    Thought about that but according to w3schools (w3schools.com/jsref/event_onchange.asp) the onchange event is only triggered by <input>, <select>, <textarea>. And <input type="button"> is different from Twitters recommended <button>.
    – Daniel O
    Feb 14, 2012 at 10:59
  • This only works in Chrome: Firefox and other browsers will not trigger the change event due to the way Bootrap (at least as of 3.0) works. Sep 30, 2013 at 20:11
  • 1
    On the latest docs (3.0) Bootstrap seems to recommend using input type="checkbox" for the grouped buttons: getbootstrap.com/javascript/#buttons-examples Jan 10, 2014 at 5:36
9

For Bootstrap 3 the default radio/button-group structure is :

<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option1"> Option 1
    </label>
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option2"> Option 2
    </label>
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option3"> Option 3
    </label>
</div>

And you can select the active one like this:

$('.btn-primary').on('click', function(){
    alert($(this).find('input').attr('id'));
}); 
1
  • Why use the id field for a value when an input has a value attribute? Mar 3, 2015 at 13:40
6

Don't use data-toggle attribute so that you can control the toggle behavior by yourself. So it will avoid 'race-condition'

my codes:

button group template (written in .erb, embedded ruby for ruby on rails):

<div class="btn-group" id="featuresFilter">
     <% _.each(features, function(feature) { %> <button class="btn btn-primary" data="<%= feature %>"><%= feature %></button> <% }); %>
</div>

and javascript:

onChangeFeatures = function(e){
        var el=e.target;
        $(el).button('toggle');

        var features=el.parentElement;
        var activeFeatures=$(features).find(".active");
        console.log(activeFeatures);
}

onChangeFeatures function will be triggered once the button is clicked.

2
  • 1
    This helped me... I was running into an issue where my click handler would go off before the bootstrap library changed the toggle state of my button - so my code always thought the button was toggled. Definitely better to handle the toggle by yourself in more complex situations. Jul 28, 2012 at 20:05
  • Technically, there is no race condition in this scenario. Jun 18, 2014 at 11:27
3

I needed to do the same thing for a chart where you could select the period of the data that should be displayed.

Therefore I introduced the CSS class 'btn-group-radio' and used the following unobtrusive javascript one-liner:

// application.js
$(document).ready(function() {
  $('.btn-group-radio .btn').click(function() {
    $(this).addClass('active').siblings('.btn').removeClass('active');
  });
});

And here is the HTML:

<!-- some arbitrary view -->
<div class="btn-group btn-group-radio">
  <%= link_to '1W', charts_path('1W'), class: 'btn btn-default active', remote: true %>
  <%= link_to '1M', charts_path('1M'), class: 'btn btn-default', remote: true %>
  <%= link_to '3M', charts_path('3M'), class: 'btn btn-default', remote: true %>
  <%= link_to '6M', charts_path('6M'), class: 'btn btn-default', remote: true %>
  <%= link_to '1Y', charts_path('1Y'), class: 'btn btn-default', remote: true %>
  <%= link_to 'All', charts_path('all'), class: 'btn btn-default', remote: true %>
</div>
1

Looking at the example HTML for radio buttons on the Twitter Bootstrap page (http://twitter.github.com/bootstrap/base-css.html#forms), you can see that each input has a unique ID attribute, i.e. optionsRadios1 and optionsRadios2.

The relevant HTML example snippet is included here for completeness:

<div class="controls">
  <label class="radio">
    <input type="radio" checked="" value="option1" id="optionsRadios1" name="optionsRadios">
    Option one is this and that—be sure to include why it's great
  </label>
  <label class="radio">
    <input type="radio" value="option2" id="optionsRadios2" name="optionsRadios">
    Option two can is something else and selecting it will deselect option one
  </label>
</div>

So you can use a jQuery click event, and then use the this reference to look at the id of the HTML element that was clicked.

$('.controls').find('input').bind('click',function(event){
  if($(this).attr('id')==='optionsRadios1'){
    alert($(this).attr('id'));
  } else {
    //... call some other function
  }
});
1

If your html is similar to the example, so the click event is produced over the label, not in the input, so I use the next code: Html example:

<div id="myButtons" class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
  </label>      
</div>

Javascript code for the event:

$('#option1').parent().on("click", function () {
   alert("click fired"); 
});
1
  • 2
    Thanks for posting an answer to this question! Code-only answers are discouraged on Stack Overflow, because a code dump with no context doesn't explain how or why the solution will work, making it difficult for the original poster (or any future readers) to understand the logic behind it. Please, edit your question and include an explanation of your code so that others can benefit from your answer. Aug 5, 2015 at 20:00
1

I searched so many pages: I found a beautiful solution. Check it out:

git link

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

    <script>
        $(function() {
            $("#my_launch_today_chk").change(function() {
                var chk = $(this).prop('checked');
                if(chk == true){
                    console.log("On");
                }else{
                    console.log("OFF");
                }
            });
        });
    </script>
</head>
<body >

<input type="checkbox" id="my_launch_today_chk" checked data-on="Launch" data-off="OFF" data-toggle="toggle" data-size="small">
</body>
</html>

Not the answer you're looking for? Browse other questions tagged or ask your own question.