11

I want to display green checked image when checkbox is checked and when not checked empty box. I tried to put checkbox in div and set div's background but it is not helping me out. Any idea what to do? Below is the output I want.

Image

Dhwani
  • 7,484
  • 17
  • 78
  • 139
  • There are GUI alternatives that can be styled, like http://jqueryui.com/ – Pekka May 03 '13 at 06:25
  • 3
    If you want to style your checkbox take a look to this similar question http://stackoverflow.com/questions/4148499/how-to-style-checkbox-using-css – Irvin Dominin May 03 '13 at 06:28

8 Answers8

16

Here is an example, done with a little jQuery and CSS: DEMO

$(".checkbox").click(function() {
  $(this).toggleClass('checked')
});
.checkbox {
  width: 23px;
  height: 21px;
  background: transparent url(https://i.stack.imgur.com/S4p2R.png ) no-repeat 0 50%
}

.checked {
  background: transparent url(https://i.stack.imgur.com/S4p2R.png ) no-repeat 80% 50%
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div class="checkbox">
</div>
Nat Riddle
  • 928
  • 1
  • 10
  • 24
Anujith
  • 9,370
  • 6
  • 33
  • 48
  • Note that this is a very poor choice for accessibility reasons. There is no semantic meaning to the div, so it isn't selectable with the keyboard, can't be controlled using a screen reader, and won't even be treated as a form element. Take an `` and restyle that instead. – Mikkel Dec 07 '21 at 17:18
13

Someone stumbling over this while googling? Take this CSS-only approach into consideration:

input[type=checkbox] {
    display: block;
    width: 30px;
    height: 30px;
    -webkit-appearance: none;
    outline: 0;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
}

input[type=checkbox]:not(:checked) {
    background-image: url(unchecked.svg);
}

input[type=checkbox]:checked {
    background-image: url(checked.svg);
}


See this example:

input[type=checkbox] {
    display: block;
    width: 30px;
    height: 30px;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
    -webkit-appearance: none;
    outline: 0;
}
input[type=checkbox]:checked {
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve"><path id="checkbox-3-icon" fill="%23000" d="M81,81v350h350V81H81z M227.383,345.013l-81.476-81.498l34.69-34.697l46.783,46.794l108.007-108.005 l34.706,34.684L227.383,345.013z"/></svg>');
}
input[type=checkbox]:not(:checked) {
    background-image: url('data:image/svg+xml;utf8,<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve"> <path id="checkbox-9-icon" d="M391,121v270H121V121H391z M431,81H81v350h350V81z"></path> </svg>');
}
<input type="checkbox" id="check" />
<div></div>
Moritz Friedrich
  • 1,371
  • 20
  • 38
  • amazing, it's simple, works in chrome and it's css-only solution – Sunny Apr 25 '15 at 01:40
  • I recommend this answer over the accepted answer since it is pure css. – Glen Pierce Nov 14 '16 at 23:15
  • This doesn't seem to work in Firefox, Edge, or IE 11. Am I missing something? – Glen Pierce Nov 14 '16 at 23:38
  • @GlenPierce, nope, you're right - Firefox for example won't allow styling checkbox elements; you could try working around this as outlined [here](http://stackoverflow.com/questions/19145504/style-a-checkbox-in-firefox-remove-check-and-border), for example. But following [this](https://www.netmarketshare.com/browser-market-share.aspx?qprid=0&qpcustomd=1), Webkit browsers cover ~60% of desktop and ~90% of the mobile market share. Decide for yourself if this is good enough :-) – Moritz Friedrich Nov 14 '16 at 23:49
  • This is the most elegant method I have seen for checkboxes... – Keval Domadia Aug 04 '21 at 07:02
10

As others have said, you can use a proxy element (div) and change checkbox state checked/unchecked when the div is clicked. Following is the working example of exactly what you require: (i have used simple javascript so that the readers can understand it quickly)

Step by step guide:

1) First of all create two css classes one for checked state and one for unchecked state:

.image-checkbox {
    background:url(unchecked.png);
    width:30px;
    height:30px;
}

.image-checkbox-checked {
    background:url(checked.png);
    width:30px;
    height:30px;
}

2) Create the HTML for DIVs and Checkboxes. The idea is that for each checkbox (input type=checkbox) we will have a div. The id of the div will be suffixed by the word proxy so that we can identify it. Also for each proxy div we will assign the initial class .image-checkbox. Let say we create two checkboxes:

<div id="checkbox1_proxy" class="image-checkbox" />
<div id="checkbox2_proxy" class="image-checkbox" />

Originl Checkboxes (hide it with style property [visibility: hidden])

<input id="checkbox1" name="checkbox1" type="checkbox"  />
<input id="checkbox2" name="checkbox2" type="checkbox"  />

3) Now we will need some javascript code to set checkbox to checked/unchecked when the proxy elements (DIVs) are clicked. Also we need to change the background image of Proxy divs according to the current state of checkbox. We can call a function to attach event handlers when the document is loaded:

<body onload="load()">

<script type="text/javascript">
function load() {
    var all_checkbox_divs = document.getElementsByClassName("image-checkbox");

    for (var i=0;i<all_checkbox_divs.length;i++) {

        all_checkbox_divs[i].onclick = function (e) {
            var div_id = this.id;
            var checkbox_id =div_id.split("_")[0];
            var checkbox_element = document.getElementById(checkbox_id);

            if (checkbox_element.checked == true) {
                checkbox_element.checked = false;
                this.setAttribute("class","image-checkbox");
            } else {
                checkbox_element.checked = true;
                this.setAttribute("class","image-checkbox-checked");
        }

        };
    }

}
</script>

Thats all... i hope it helps

asim-ishaq
  • 2,190
  • 5
  • 32
  • 55
1

One solution is to make div instead of checkbox and set a background as you want and then use js to make behaviour of the div as it was checkbox, so add onClick actions.

sylwia
  • 381
  • 1
  • 8
1

Know this is an older thread -- but needed a solution to converting checkboxes to images. :) Here's a jQuery version that works great for me - wanted to share.

function setCheckboxImageSrc(checkbox, image, checkedUrl, uncheckedUrl) {
    if (checkbox.is(":checked")) {
        image.attr("src", checkedUrl);
    } else {
        image.attr("src", uncheckedUrl);
    }
}

function setCheckboxImage(checkboxObj, className, checkedUrl, uncheckedUrl) {
    checkboxObj.hide();

    var $image = $("<img src='" + checkedUrl + "' />").insertAfter(checkboxObj);
    setCheckboxImageSrc(checkboxObj, $image, checkedUrl, uncheckedUrl);

    $image.click(function () {
        var $checkbox = $image.prev("." + className);
        $checkbox.click();
        setCheckboxImageSrc($checkbox, $image, checkedUrl, uncheckedUrl);
    });
}

$(".checkboxUp").each(function () {
    setCheckboxImage($(this), "checkboxUp", "../../../images/DirectionUpChecked.png", "../../../images/DirectionUpUnchecked.png");
});

$(".checkboxDown").each(function () {
    setCheckboxImage($(this), "checkboxDown", "../../../images/DirectionDownChecked.png", "../../../images/DirectionDownUnchecked.png");
});
1

Inspired by @asim-ishaq's answer, here is a jquery based solution that also takes into account the fact that the user can toggle the checkbox by clicking on the label tag:

<style>
    div.round-checkbox {
        background: transparent url(/css/icons-sprite.png) no-repeat -192px -72px;
        height: 24px;
        width: 24px;
        display: inline-block;

    }

    div.round-checkbox.checked {
         background: transparent url(/css/icons-sprite.png) no-repeat -168px -72px;
     }

    input.round-checkbox {
        display: none;
    }
</style>

<div class="round-checkbox" data-id="subscribe-promo-1"></div>
<input type='checkbox' class="round-checkbox" name='subscribe' value='1' id="subscribe-promo-1" />
<label for="subscribe-promo-1">I want to subscribe to offers</label>


<script>
    $(document).ready(function () {
        var jRoundCheckbox = $('input.round-checkbox');

        /**
         * Init: if the input.checkbox is checked, show the checked version of the div.checkbox,
         * otherwise show the unchecked version
         */
        jRoundCheckbox.each(function () {
            var id = $(this).attr('id');
            if ($(this).prop('checked')) {
                $('.round-checkbox[data-id="' + id + '"]').addClass("checked");
            }
            else {
                $('.round-checkbox[data-id="' + id + '"]').removeClass("checked");
            }
        });

        /**
         * If the user clicks the label, it will check/uncheck the input.checkbox.
         * The div.checkbox should reflect this state
         */
        jRoundCheckbox.on('change', function () {
            var id = $(this).attr('id');
            $('.round-checkbox[data-id="' + id + '"]').toggleClass("checked");
            return false;
        });

        /**
         * When the user clicks the div.checkbox, it toggles the checked class;
         * also, the input.checkbox should be synced with it
         */
        $('div.round-checkbox').on('click', function () {
            var id = $(this).attr('data-id');
            var jInput = $('#' + id);
            jInput.prop("checked", !jInput.prop('checked'));
            $(this).toggleClass("checked");
            return false;
        });
    });
</script>
ling
  • 9,545
  • 4
  • 52
  • 49
1

Here is another example. Works fine on Ionic v1. CSS

input[type=checkbox] {
    display: none;
}

 :checked+img {
    content: url('/img/active.png');
}

HTML

    <label>
    <input type="checkbox" ng-model="anything">
    <img style="height:30px;" src="img/deactive.png">
    </label>
    <span>{{anything}}</span>
abdullah
  • 171
  • 1
  • 2
  • 7
0

Javascript:

function myFunction() {
  var checkBox = document.getElementById("myCheck");
  var text = document.getElementById("image");
  if (checkBox.checked == true){
    text.style.display = "block";
  } else {
     text.style.display = "none";
  }
}

HTML:

<p>Display Image when the checkbox is checked:</p>
<label for="myCheck">Checkbox:</label> 
<input type="checkbox" id="myCheck" onclick="myFunction()">
<p id="image" style="display:none"><img src="https://noticetoday.in/wp-content/uploads/2021/07/Untitled-5-420x200.jpg"></p>

i hope this example can helps you.