Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a div that acts like an html checkbox

I want to turn on/off the div on click (it should act like an html checkbox) and make visible changes using css. Is this possible without Javascript, or would I have to use Javascript?

If you have created such a script please share it.

Thank you for your help in advance.

like image 485
Php Beginner Avatar asked Apr 02 '11 12:04

Php Beginner


People also ask

How do I make a div act like a checkbox?

If you only use input[type=checkbox] in the CSS, you will apply the rule to any checkbox on the page. By using #checkboxes you only apply it to checkboxes that are in a div with id="checkboxes" .

How can you make a checkbox HTML?

The <input type="checkbox"> defines a checkbox. The checkbox is shown as a square box that is ticked (checked) when activated. Checkboxes are used to let a user select one or more options of a limited number of choices. Tip: Always add the <label> tag for best accessibility practices!

How do you make a div clickable in HTML?

The <div> (or whatever wrapper element) remains semantic and accessible, while being “clickable” over the whole area. It doesn't break text selection and respects other “nested” interactive elements. And remember you can make links display: block; , so the whole rectangular area becomes “clickable”.

How do I make a checkbox always checked in HTML?

The checked attribute is a boolean attribute. When present, it specifies that an <input> element should be pre-selected (checked) when the page loads. The checked attribute can be used with <input type="checkbox"> and <input type="radio"> . The checked attribute can also be set after the page load, with a JavaScript.


1 Answers

You could do this very easily with only CSS code by hiding the checkboxes and styling their labels like so:

HTML

<div id="checkboxes">
    <input type="checkbox" name="rGroup" value="1" id="r1" checked="checked" />
    <label class="whatever" for="r1"></label>
    <input type="checkbox" name="rGroup" value="2" id="r2" />
    <label class="whatever" for="r2"></label>
    <input type="checkbox" name="rGroup" value="3" id="r3" />
    <label class="whatever" for="r3"></label>
</div>

CSS

.whatever{
    background-color: red;
    display: inline-block;
    width: 100px;
    height: 100px;
}

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

#checkboxes input[type=checkbox]:checked + .whatever{
    background-color: green;
}

You can take a look at this simple code in action here:
JSFiddle

Hope this helps! :)

like image 72
nicosemp Avatar answered Oct 19 '22 22:10

nicosemp