Skip to content Skip to sidebar Skip to footer

Replacing Checkboxes With Images?

I am trying to replace three check boxes within an html form with three different images. The idea being that the user can select the pictures by clicking on them rather than click

Solution 1:

Why use JavaScript at all? You can do this with CSS, the :checked attribute and a label element.

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

:checked+img {
  border: 2px solid red;
}
<label><inputtype="checkbox"name="checkbox"value="value"><imgsrc="http://lorempixel.com/50/50/"alt="Check me"></label>

Solution 2:

This is happening because you're using the same ID more than one. IDs should be unique. Instead of using id="blr", try using class="blr". I updated the fiddle:

http://jsfiddle.net/0rznu4ks/1/

Solution 3:

First, as Amar said, id should be unique. Use classes for multiple elements. Also pay attention for semicolons and closing html tags.

To your question: use the function .siblings() to get the relevant checkbox element.

$('.blr').on('click', function () {
    var $$ = $(this);
    if (!$$.is('.checked')) {
        $$.addClass('checked');
        $$.siblings('input.imgCheck').prop('checked', true);
    } else {
        $$.removeClass('checked');
        $$.siblings('input.imgCheck').prop('checked', false);
    }
});

See demo here: http://jsfiddle.net/yd5oq032/1/

Good luck!

Post a Comment for "Replacing Checkboxes With Images?"