Skip to content

Instantly share code, notes, and snippets.

@tacone
Last active December 17, 2015 07:49
Show Gist options
  • Save tacone/5575634 to your computer and use it in GitHub Desktop.
Save tacone/5575634 to your computer and use it in GitHub Desktop.
Boolean field for a search box: Sample progressive enhancement boolean Selectbox (null, true, false) to 3-state-button using jQuery and Bootstrap. Case use: an advanced search box, with boolean fields allowing to either filter by true, false or not filter at all.
+function() {
var buttons = $('.container select').map(function() {
var $select = $(this);
var $options = $select.find('option');
var $button = null;
var updateUi = function() {
var normalizedVal = $select.val() != '' ? parseInt($select.val()): null;
switch (normalizedVal)
{
case null:
$button.find('small').html(' ');
$button.toggleClass('btn-success', false);
$button.toggleClass('btn-danger', false);
$button.toggleClass('active', false);
break;
case 1:
$button.find('small').html('with:');
$button.toggleClass('btn-success', true);
$button.toggleClass('btn-danger', false);
$button.toggleClass('active', true);
break;
case 0:
default:
$button.find('small').html('without:');
$button.toggleClass('btn-success', false);
$button.toggleClass('btn-danger', true);
$button.toggleClass('active', true);
break;
}
}
if ($options.length == 3
&& $($options.get(0)).val() == ''
&& parseInt($($options.get(1)).val()) == 1
&& parseInt($($options.get(2)).val()) == 0
) {
var $label = $select.prevAll('label').first();
$label.css({visibility: 'hidden'});
$select.parents('div[class*="span"]').first().css({display: 'none'});
$button = $('<button type="button" class="btn btn-checkbox">')
.html("<small>&nbsp;</small><br/>" + $label.html())
.click(function() {
var normalizedVal = $select.val() != '' ? parseInt($select.val()): null;
switch ( normalizedVal )
{
case null:
$select.val("1");
break;
case 1:
$select.val("0");
break;
case 0:
default:
$select.val('');
break;
}
updateUi();
});
if ( $button.length ) updateUi();
return $button.get(0);
}
return null;
});
var group = $('<div class="btn-group">').append(buttons);
$('.container .alert-filters .row-fluid .span3').last().after(group.wrap('<div class="span12">'));
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment