Using jQuery and Bootstrap to Enhance Checkbox Button Styling

I am currently working on an asp.net webform and attempting to style my checkbox similar to the design shown here:

When I try to replicate the HTML and JS code from the above link on my page, it does not seem to be functioning properly, most likely due to missing CSS or other elements...

Could someone kindly provide a comprehensive example (including HTML, CSS, and script) of what I need to add to my page in order to achieve the checkbox appearance depicted in the image above?

Here is the code snippet from the aforementioned link, which can also be tested here: http://jsfiddle.net/DcYhf/65/

However, when I implement it on my own page, it does not seem to work properly...

HTML

<span class="button-checkbox">
        <button type="button" class="btn btn-lg" data-color="primary">Primary</button>
        <input type="checkbox" class="hidden" checked />
    </span>

JS

$(function () {
    $('.button-checkbox').each(function () {

        // Settings
        var $widget = $(this),
            $button = $widget.find('button'),
            $checkbox = $widget.find('input:checkbox'),
            color = $button.data('color'),
            settings = {
                on: {
                    icon: 'glyphicon glyphicon-check'
                },
                off: {
                    icon: 'glyphicon glyphicon-unchecked'
                }
            };

        // Event Handlers
        $button.on('click', function () {
            $checkbox.prop('checked', !$checkbox.is(':checked'));
            $checkbox.triggerHandler('change');
            updateDisplay();
        });
        $checkbox.on('change', function () {
            updateDisplay();
        });

        // Actions
        function updateDisplay() {
            var isChecked = $checkbox.is(':checked');

            // Set the button's state
            $button.data('state', (isChecked) ? "on" : "off");

            // Set the button's icon
            $button.find('.state-icon')
                .removeClass()
                .addClass('state-icon ' + settings[$button.data('state')].icon);

            // Update the button's color
            if (isChecked) {
                $button
                    .removeClass('btn-default')
                    .addClass('btn-' + color + ' active');
            }
            else {
                $button
                    .removeClass('btn-' + color + ' active')
                    .addClass('btn-default');
            }
        }

        // Initialization
        function init() {

            updateDisplay();

            // Inject the icon if applicable
            if ($button.find('.state-icon').length == 0) {
                $button.prepend('<i class="state-icon ' + settings[$button.data('state')].icon + '"></i> ');
            }
        }
        init();
    });
});

This is my current implementation:

Answer №1

I have come across a working example:

$(function () {
    $('.button-checkbox').each(function () {

        // Configuration
        var $widget = $(this),
            $button = $widget.find('button'),
            $checkbox = $widget.find('input:checkbox'),
            color = $button.data('color'),
            settings = {
                on: {
                    icon: 'glyphicon glyphicon-check'
                },
                off: {
                    icon: 'glyphicon glyphicon-unchecked'
                }
            };

        // Event Handlers
        $button.on('click', function () {
            $checkbox.prop('checked', !$checkbox.is(':checked'));
            $checkbox.triggerHandler('change');
            updateDisplay();
        });
        $checkbox.on('change', function () {
            updateDisplay();
        });

        // Actions
        function updateDisplay() {
            var isChecked = $checkbox.is(':checked');

            // Set button state
            $button.data('state', (isChecked) ? "on" : "off");

            // Set button icon
            $button.find('.state-icon')
                .removeClass()
                .addClass('state-icon ' + settings[$button.data('state')].icon);

            // Update button color
            if (isChecked) {
                $button
                    .removeClass('btn-default')
                    .addClass('btn-' + color + ' active');
            }
            else {
                $button
                    .removeClass('btn-' + color + ' active')
                    .addClass('btn-default');
            }
        }

        // Initialization
        function init() {

            updateDisplay();

            // Insert icon if needed
            if ($button.find('.state-icon').length === 0) {
                $button.prepend('<i class="state-icon ' + settings[$button.data('state')].icon + '"></i> ');
            }
        }
        init();
    });
});
var new_checkbox_button = function(name,id){
    return "<li><span class='button-checkbox'><button type='button' class='btn btn-sm btn-primary active' data-color='primary'><i class='state-icon glyphicon glyphicon-check'></i>&nbsp;"+name+"</button><input type='checkbox' class='hidden' checked=''></span></li>";
};
$("#add").click(function(){
    $("#selected_targets").append(new_checkbox_button("lallalala","1111"));
});
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css" rel="stylesheet"/>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Existing checkboxes</p>
    <span class="button-checkbox">
        <button type="button" class="btn" data-color="default">Default</button>
        <input type="checkbox" class="hidden" checked />
    </span>
    <span class="button-checkbox">
        <button type="button" class="btn" data-color="primary">Primary</button>
        <input type="checkbox" class="hidden" checked />
    </span>
    <span class="button-checkbox">
        <button type="button" class="btn" data-color="success">Success</button>
        <input type="checkbox" class="hidden" checked />
    </span>
    <span class="button-checkbox">
        <button type="button" class="btn" data-color="info">Info</button>
        <input type="checkbox" class="hidden" checked />
    </span>
    <span class="button-checkbox">
        <button type="button" class="btn" data-color="warning">Warning</button>
        <input type="checkbox" class="hidden" checked />
    </span>
    <span class="button-checkbox">
        <button type="button" class="btn" data-color="danger">Danger</button>
        <input type="checkbox" class="hidden" checked />
    </span>
    <span class="button-checkbox">
        <button type="button" class="btn" data-color="link">Link</button>
        <input type="checkbox" class="hidden" checked />
    </span>
<br/><br/><br/>
<p> New checkboxes</p>
<button id="add">click to add checkbox</button>
<ui id="selected_targets"></ui>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery append() is ineffective

I am having trouble with the append() function in all browsers. My goal is to have the "next" span display the text "Next hello" with a blue background when the page loads. (This code serves as a test to confirm that my jQuery is functioning properly. In ...

contrasts in regex special characters: .net versus javascript

Here is my current javascript implementation: EscapeForRegex = function(input) { var specials = ["[", "\\", "^", "$", ".", "|", "?", "*", "+", "(", ")", "{", "}"] for (var k in specials) { var special = specials[k]; ...

Unable to locate the node module within the Rails stimulus controller

I'm facing an issue with integrating my own npm package into a Rails application that I have developed. It's unclear whether the problem lies in the creation of the node package or within the rails app itself. The package in question is fairly ...

The terser-webpack-plugin and uglifyjs-webpack-plugin are both powerful tools for optimizing

WebPack 4 now utilizes the terser-webpack-plugin in production mode or when the -p argument is specified, which essentially means including --optimize-minimize --define process.env.NODE_ENV="production". This plugin is responsible for minimizing ...

Asserting types for promises with more than one possible return value

Struggling with type assertions when dealing with multiple promise return types? Check out this simplified code snippet: interface SimpleResponseType { key1: string }; interface SimpleResponseType2 { property1: string property2: number }; inter ...

Tips for adjusting the height and border of Bootstrap tabs

I'm facing an issue with the modal and nav-tabs I created. There are a couple of problems that need to be addressed. Firstly, the tabs have excessive height and I've tried adjusting it using CSS height property, but it's not working as e ...

Swapping out the entire vue.js container

I have a custom vue.js widget that I initialize like so: var myWidget = new Vue({ el: '#widget-container', methods: { loadData:function() { // custom functionality here } }, }); The HTML structure is as f ...

Revolutionary newspaper design utilizing asp.net's C# web forms

Trying to create a dynamic newspaper layout using ASP.NET C# web form. Struggling to set the page layout size inside a slider and display specific news content on a new page when clicking on an area of the newspaper using Repeater or another suitable contr ...

Comparing global variables in ng-switch: Best practices

I'm currently utilizing the AngularJS $rootScope object to expose some global constants that should be accessible to both controllers and views: var app = angular.module('myApp', []); app.run(function ($rootScope) { $rootScope.myConsta ...

Creating custom mesh Morph Target Animations using THREE.js

I'm currently working on creating an animation that showcases the revolution of a 2D function around an axis to produce a 3D surface. Successfully rendering the surface, my next task is to implement the animation section using MorphTargets. Despite m ...

Guide on converting JSON to CSV in React by utilizing the map function

When I convert JSON data to CSV by clicking a button, it currently stores the data in the CSV file separated by commas. However, I want each piece of data to be on its own line. How can I achieve this? For example: Minor,Minor What I Want: Each item on a ...

Transforming the Current Page of a GridView into a DataSet or DataTable

Similar Question: GridView current page I am working with a GridView and have enabled paging on it. Is there a way to convert the content of the current page of the gridview into a DataTable using extension methods or techniques? Any help on this wo ...

Modify individual list item attributes

I have been attempting to modify the background of the list item labeled as home in order to ensure that it displays hover properties even when not being interacted with. Despite specifying this in the class, the appearance does not change. Below is the H ...

Unable to retrieve data. Issue: Unable to send headers after they have already been sent to the client

Experiencing an error while attempting to retrieve posts from a specific user. The code for fetching the data appears to be correct, so it's unclear where the error is originating from. Error from server side https://i.stack.imgur.com/ep1Xh.png Error ...

Display a loading spinner with ReactJS while waiting for an image to load

I am working on a component that renders data from a JSON file and everything is functioning correctly. However, I would like to add a loading spinner <i className="fa fa-spinner"></i> before the image loads and have it disappear once the ima ...

Can you explain the difference between synchronous and asynchronous loading?

After exploring this website, I have learned that when using CommonJS, the browser loads files one by one after downloading them, which can lead to dependencies slowing down the process. However, with AMD, multiple files can be loaded simultaneously, all ...

Can I issue multiple SADD or ZADD commands in a single .sadd/.zadd call using ioredis?

I'm currently experimenting with ioredis for caching and indexing a substantial volume of data. However, my searches haven't yet yielded information on whether it supports performing multiple SADDs in one call. Can this be done, and if so, are t ...

Determine the parent sibling of the image wrapper by using the specified selector

I am trying to write code that, when a button is clicked on, will find the parent elements' siblings (specifically an image within an "img_wp" div). However, my current code doesn't seem to be working. Can anyone spot where I might have gone wron ...

Error encountered: Multer TypeError - fields does not have a function called forEach

I'm currently working on a metadata reader using multer in node.js with express on c9. I've spent some time searching for solutions to my issue, but it seems like no one else has encountered the error I am facing: TypeError: fields.forEach is no ...

Resolving the CORS predicament caused by the ionic/angular's HTTP interceptor

I am currently using Ionic for both web and mobile development. However, I have encountered a CORS issue when integrating it with an HTTPS URL. Interestingly, the issue seems to be resolved after removing the HTTP interceptor. Nevertheless, I am seeking a ...