Skip to main content
  1. Archive/

Twitter Bootstrap Radio Button Form Inputs

·2 mins

I’ve been loving the Twitter Bootstrap buttons so I came up with a quick technique that turns them into actual working form input elements.

HTML #

Just like a normal Bootstrap Button Group, but with a few added attributes.

<div class="btn-group" data-toggle-name="is_private" data-toggle="buttons-radio">
  <button type="button" value="0" class="btn" data-toggle="button">Public</button>
  <button type="button" value="1" class="btn" data-toggle="button">Private</button>
</div>
<input type="hidden" name="is_private" value="0" />

Note: Yes, nested names like bookmark[is_private] work just fine.

JavaScript #

On document load we apply the button logic and state based on the hidden input’s value.

jQuery(function($) {
  $('div.btn-group[data-toggle-name=*]').each(function() {
    var group   = $(this);
    var form    = group.parents('form').eq(0);
    var name    = group.attr('data-toggle-name');
    var hidden  = $('input[name="' + name + '"]', form);
    $('button', group).each(function(){
      var button = $(this);
      button.on('click', function(){
        hidden.val($(this).val());
      });
      if(button.val() == hidden.val()) {
        button.addClass('active');
      }
    });
  });
});

The Result #

Twitter Bootstrap Radio Button Form Inputs Result

Notes & Considerations #

  • This solution requires JavaScript in order to work properly so use judgement when implementing it.
  • The type="button" is required to prevent the form getting submitted when the toggle buttons are clicked.
  • You may also need to do some styling to get the buttons to look right in some contexts. Thankfully I’ve found this to be a relatively painless experience.

Summary #

Please comment or contact me if you find any issues. I’ve tested this technique and so far I’ve been very happy with it.