Last active
December 5, 2015 18:32
-
-
Save gskema/5c5420401faf781b419c to your computer and use it in GitHub Desktop.
Bootstrap 3 Numeric Up and Down control (spinbox, spinner)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="spinbox" data-min="1" data-max="10" data-step="2"> | |
<input class="form-control spinbox-input" type="text" value="1"> | |
<div class="spinbox-buttons"> | |
<button class="spinbox-up btn btn-default btn-xs" type="button">+</button> | |
<button class="spinbox-down btn btn-default btn-xs" type="button">-</button> | |
</div> | |
</div> | |
<script type="text/javascript"> | |
// jQuery must be available before binding events | |
$(document).on('click', '.spinbox-up, .spinbox-down', function() { | |
var $spinbox = $(this).closest('.spinbox'); | |
if ($spinbox.length) { | |
var $input = $spinbox.find('input.spinbox-input'); | |
if ($input.length) { | |
var max = parseInt($spinbox.data('max')) || false; | |
var min = parseInt($spinbox.data('min')) || false; | |
var val = parseInt($input.val()) || min || 0; | |
var sign = $(this).hasClass('spinbox-up') ? 1 : -1; | |
val += sign * (parseInt($spinbox.data('step')) || 1); | |
if (max && val > max) { | |
val = max; | |
} else if (min && val < min) { | |
val = min; | |
} | |
$input.val(val).trigger('change'); | |
} | |
} | |
}); | |
// Now you may attach events to the spinbox: | |
$('.spinbox-input').on('change', function() { | |
console.log('Spinbox value has been changed!') | |
}); | |
</script> | |
<style type="text/css"> | |
.spinbox { | |
max-width: 60px; | |
position: relative; | |
padding-right: 20px; | |
} | |
.spinbox .spinbox-input { | |
min-width: 40px; | |
padding-left: 4px; | |
padding-right: 4px; | |
text-align: center; | |
} | |
.spinbox .spinbox-buttons { | |
text-align: center; | |
position: absolute; | |
right: 0; | |
top: 0; | |
height: 100%; | |
width: 20px; | |
} | |
.spinbox .spinbox-buttons .spinbox-up { | |
position: absolute; | |
top: 0; | |
right: 0; | |
height: 50%; | |
width: 100%; | |
border-left: none; | |
line-height: 1; | |
} | |
.spinbox .spinbox-buttons .spinbox-down { | |
position: absolute; | |
bottom: 0; | |
right: 0; | |
height: 50%; | |
width: 100%; | |
border-left: none; | |
line-height: 1; | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment