Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to gray out an html checkbox?

I want to make readonly checkbox. Like this:

<input type="checkbox" onclick="return false;">

I want the checkbox to look like it is disabled or grayed out.

How can I do this?

like image 590
Roman Avatar asked May 21 '12 12:05

Roman


People also ask

How do I change the color of a checkbox in HTML?

“:hover” is used to style the checkbox when user hovers over it. Notice that when the mouse pointer move over the checkbox the color of it changes to yellow. “:active” is used to style the checkbox when it is active. Notice that when click the checkbox it will first notice a red color and then the green color.

How do I make checkboxes disabled in CSS?

Use input type="hidden" to store information and process it using JS.


4 Answers

You need to disable the checkbox also:

<input type="checkbox" onclick="return false;" disabled="disabled">

To post the value, simply make it readonly instead:

<input type="checkbox" onclick="return false;" readonly="readonly">

You can style checkbox label and readonly inputs with CSS, e.g.: input [readonly="readonly"] {} but the browser should make the checkbox should appear greyed out when set to readonly.

Updated:

You are at the the mercy of the browser when styling checkboxes & to style them consistently across all browsers, you have to resort to images e.g.: https://archive.is/TNUH1

If you don't want to do this (and it seems like a longwinded solution), the simplest solution is to disable the checkbox so it appears correctly, and post the value as a hidden input e.g.:

<input type="checkbox" onclick="return false;" disabled="disabled">
<input type="hidden" name="checkboxval" value="111" />
like image 60
FluffyKitten Avatar answered Oct 12 '22 08:10

FluffyKitten


simply add the 'disabled' attribute on checkbox like this

<input type="checkbox" disabled="disabled" />
like image 23
Talha Avatar answered Oct 12 '22 08:10

Talha


Simple, css-only way to gray-out a disabled checkbox.

input[type=checkbox][disabled] {
    filter: invert(25%);
}
like image 26
Christian Long Avatar answered Oct 12 '22 08:10

Christian Long


$('input.readonly').on('click', function(evt) {
   evt.preventDefault();
});
input.readonly {
   opacity: .5;
   filter: alpha(opacity=50); /* IE<9 */
   cursor: default;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="readonly">

Add a class readonly to the element you want to grayout: via css you set an opacity and change the style of cursor. Then remove inline javascript and prevent the default action for input.readonly elements on click event

like image 42
Fabrizio Calderan Avatar answered Oct 12 '22 08:10

Fabrizio Calderan