Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Adding dynamic functionality to Bootstrap 3 slider switches
// Note! Use a radio button for this, not a checkbox!
// You need to check your database to find out the switch value
// e.g. <?php $switch_val = DB::only("SELECT switch FROM table WHERE user_id = $user_id"); ?>
// In your view/HTML
<script>
var switch = !!Number('<?php echo $switch_val ?>');
switch ? $('.slider-button').addClass('on') : $('.slider-button').removeClass('on');
switch ? $('.slider-button').text('ON') : $('.slider-button').text('OFF');
</script>
// In your main JS file
// Slide switch and update value of radio button
$('.slider-button').click(function() {
if ($('[name="radio_input"]').val() == '1') {
$(this).removeClass('on').text('OFF');
$('[name="radio_input"]').val('0');
} else {
$(this).addClass('on').text('ON');
$('[name="radio_input"]').val('1');
}
});
// Done!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment