Wednesday, April 24, 2013

Twitter Bootstrap JS: Using ButtonGroup (radio type) selected button in a form

This is the function that we use to watch which buttons have been activated in a Twitter Bootstrap `buttonGroup` of a radio type.  You need to have a hidden form field so the function can put the values from the selected buttons in there for your form post.

Using it is as simple as adding this to your document ready of your page.  The first argument of the function call is the id of the `buttonGroup` and the second argument is the id of the hidden input where the function will store the values of the activated buttons:
    $(document).ready(function() {
        watchButtonsRadio('#utilitiesLocatedBtnGroup', '#utilities_located');

Add this function to the general or utility JS file that is loaded on every page:
function watchButtonsRadio(buttonGroup, hiddenInput) {
    $('button', $(buttonGroup)).each(function() {

        var originalValue = $(hiddenInput).val();

        //Convert booleans to numeric
        if (originalValue == 'true') {
            originalValue = 1;
        } else if (originalValue == 'false') {
            originalValue = 0;

        if ($(this).val() == originalValue) {

        $(this).live('click', function() {
            // Hidden by default doesn't trigger the change event so manually fire it
            console.log(hiddenInput + ': ' + $(hiddenInput).val());

No comments:

Post a Comment