Readonly checkboxes with JQuery

I have encountered a problem where i needed to disable some checkboxes on my forms. As you know, a disabled html item by design isn’t going to be posted back. So i needed to figure out another solution. So with the disabled tag, we have a readonly tag, which just blurs the checkbox, but lets the user click on it and change the value(i was testing this in Chrome, i don’t know what happens in other browsers).

The solution is:

1. Make your checkboxes readonly by setting the readonly attribute to true

<%= check_box_tag "some_id", :readonly => true %>

2. Put this javascript in your document.load so the click will be overridden:

// Javascript:

$(':checkbox[readonly="readonly"]').click(function() {
return false;
});

// Coffeescript:

$(':checkbox[readonly="readonly"]').click ->
false

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.