How to set a checkbox value in code - html

Hi I have some code like:
foreach (var item in Model) {
<div>
#Html.DisplayFor(modelItem => item.UserRole.Role.Name)
</div>
<div>
<input type="checkbox" name="ids" checked="#item.Active" />
</div>
}
What I was trying to achieve was set the checkbox check if item is Active else not checked.
I understand the syntax should be checked="checked" and I've set it up as checked="true"
I don't understand how to convert the true to checked and what to do for false.
I was trying to use a ternary but it wouldn't play nice. Can anybody help?

The presence of the checked attribute will cause it to be checked, i.e It doesn't matter (AFAIK) what the value of the attribute is. So you need to detect whether or not to add the checked attribute at all:
foreach (var item in Model)
{
<div>
#Html.DisplayFor(modelItem => item.UserRole.Role.Name)
</div>
<div>
<input type="checkbox" name="ids" #if (item.Active) { Write("checked"); }/>
</div>
}
Edited: changed to MДΓΓ БДLL version, much cleaner.
One brute force approach =P

I understand the syntax should be checked="checked"
If you are using XHTML, that is true. In HTML the shorthand syntax is recommended where you specify only the value of that attribute (although user agents don't have a problem with the long for these days, it is quicker to type).
<input type="checkbox" name="foo" value="bar" checked>
I don't understand how to convert the true to checked
That depends on the (unspecified) template language you are using.
and what to do for false.
Don't include the checked attribute at all.
<input type="checkbox" name="foo" value="bar">

In HTML, to uncheck it, just remove the checked="whatever" attribute. Technically, HTML doesn't care what the value of checked="" is, just that it exists and that it's valid markup.

Related

Using checkboxes without a value attribute

I Understand the ins and outs of forms, but say for example I have the following code:
<form method="post" action="urltoserver">
<input type="checkbox" name="mycheckbox" value="1">Question</input>
</form>
Here I have set a value for the $_POST array. However, if I simply want to know if the checkbox is selected or not (ie im not bothered about the returned value), is it feasible/common practice to leave off the value attribute all together? Would it just return true/false in this case?
I'm assuming PHP since you mentioned $_POST; correct me if I'm wrong.
if a checkbox is checked (and there is no value assigned) you should (IIRC) receive an on value back (as unchecked boxes aren't sent with the request). So, if you had:
<form method="POST">
<input type="checkbox" name="foo" /> Foo
<input type="checkbox" name="bar" checked="checked"/> Bar
<input type="checkbox" name="baz" checked="checked"/> Baz
</form>
You'd see:
isset($_POST['foo']) == false
isset($_POST['bar']) == true
isset($_POST['baz']) == true
on the server-side when you went to read the check state.
the easiest thing to do though, if you're learning, is submit it to a page with the following code:
<?php
var_dump($_REQUEST);
That will show you, verbatim, what was submitted (based on the form's populated values). From there you can play with how you want to format the form to receive the values you're expecting.

What does the value attribute mean for checkboxes in HTML?

Suppose this checkbox snippet:
<input type="checkbox" value="1">Is it worth?</input>
Is there any reason to statically define the value attribute of checkboxes in HTML? What does it mean?
I hope I understand your question right.
The value attribute defines a value which is sent by a POST request (i.e. You have an HTML form submitted to a server).
Now the server gets the name (if defined) and the value.
<form method="post" action="urlofserver">
<input type="checkbox" name="mycheckbox" value="1">Is it worth?</input>
</form>
The server would receive mycheckbox with the value of 1.
in PHP, this POST variable is stored in an array as $_POST['mycheckbox'] which contains 1.
I just wanted to make a comment on Adriano Silva's comment.
In order to get what he describes to work you have to add "[]" at the end of the name attribute, so if we take his example the correct syntax should be:
<input type = "checkbox" name="BrandID[]" value="1">Ford</input>
<input type = "checkbox" name="BrandID[]" value="2">GM</input>
<input type="checkbox" name="BrandId[]" value="3">Volkswagen</input>
Then you use something like: $test = $_POST['BrandID']; (Mind no need for [] after BrandID in the php code).
Which will give you an array of values, the values in the array are the checkboxes that are ticked's values.
Hope this helps! :)
One reason is to use the ease of working with values ​​in the system.
<input type="checkbox" name="BrandId" value="1">Ford</input>
<input type="checkbox" name="BrandId" value="2">GM</input>
<input type="checkbox" name="BrandId" value="3">Volkswagen</input>
When the form is submitted, the data in the value attribute is used as the value of the form input if the checkbox is checked. The default value is "on".
$('form').on('change', update).trigger('change')
function update() {
var form = $(this)
form.find('output').text('→ ' + form.serialize())
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="foo">
<output></output>
</form>
<form>
<input type="checkbox" name="foo" checked>
<output></output>
</form>
<form>
<input type="checkbox" name="foo" value="1" checked>
<output></output>
</form>
<form>
<input type="checkbox" name="foo" value="bananas" checked>
<output></output>
</form>
For the sake of a quick glance answer, from MDN
when a form is submitted, only checkboxes which are currently checked are submitted to the server, and the reported value is the value of the value attribute
It can be confusing because seeing something like
<input type='checkbox' name='activated' value='1'> might lead one to believe that the 1 means true and it will be treated as though it is checked, which is false. The checked attribute itself also only determines if the checkbox should be checked by default on page load, not whether it is currently checked and thus going to be submitted.

What is the proper way to check and uncheck a checkbox in HTML5?

Looked at the HTML spec, but couldn't make heads or tails of it: http://www.w3.org/TR/html5/the-input-element.html#attr-input-checked
What is the correct way to check a checkbox in HTML (not dynamically)?
checked="true"
checked="checked"
What is the correct way to uncheck a checkbox?
<input type="checkbox" /> with no checked attribute
checked="false"
checked="none"
Where to check the HTML specification to check/uncheck a checkbox?
For checked state
Older browsers may need:
<input type="checkbox" checked="checked" />
But nowadays simply do:
<input type="checkbox" checked />
For unchecked state
Remove checked attribute, like:
<input type="checkbox" />
Reference: http://www.w3.org/TR/html-markup/input.checkbox.html#input.checkbox.attrs.checked
According to HTML5 drafts, the checked attribute is a “boolean attribute”, and “The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.” It is the name of the attribute that matters, and suffices. Thus, to make a checkbox initially checked, you use
<input type=checkbox checked>
By default, in the absence of the checked attribute, a checkbox is initially unchecked:
<input type=checkbox>
Keeping things this way keeps them simple, but if you need to conform to XML syntax (i.e. to use HTML5 in XHTML linearization), you cannot use an attribute name alone. Then the allowed (as per HTML5 drafts) values are the empty string and the string checked, case insensitively. Example:
<input type="checkbox" checked="checked" />
<input type="checkbox" checked />
HTML5 does not require attributes to have values
In jQuery:
To check the checkbox:
$("#checkboxid").attr("checked","checked");
To uncheck the checkbox:
$("#checkboxid").removeAttr("checked");
The other answers hint at the solution and point you to documentation that after further digging will get you to this answer. Jukka K. Korpela has the reason this is the correct answer, basically I followed his link and then looked up the jQuery docs to get to that result. Just figured I'd save future people who find this article those extra steps.
you can use autocomplete="off" on parent form, so if you reload your page, checkboxes will not be checked automatically
Complementary answer to Robert's answer http://jsfiddle.net/ak9Sb/ in jQuery
When getting/setting checkbox state, one may encounter these phenomenons:
.trigger("click");
Does check an unchecked checkbox, but do not add the checked attribute.
If you use triggers, do not try to get the state with "checked" attribute.
.attr("checked", "");
Does not uncheck the checkbox...
I'm not entirely sure why this hasn't been mentioned before, but for me, the following works:
To set it to checked:
<input type="checkbox" checked>
To set it to unchecked:
<input type="checkbox" unchecked>
(I was having the problem that checkboxes remained checked after reloading the page. Using unchecked solved my problem, so it might be useful to someone else.)
You can refer to this page at w3schools but basically you could use any of:
<input checked>
<input checked="checked">
<input checked="">
<form name="myForm" method="post">
<p>Activity</p>
skiing: <input type="checkbox" name="activity" value="skiing" checked="yes" /><br />
skating: <input type="checkbox" name="activity" value="skating" /><br />
running: <input type="checkbox" name="activity" value="running" /><br />
hiking: <input type="checkbox" name="activity" value="hiking" checked="yes" />
</form>

What's the proper value for a checked attribute of an HTML checkbox?

We all know how to form a checkbox input in HTML:
<input name="checkbox_name" id="checkbox_id" type="checkbox">
What I don't know -- what's the technically correct value for a checked checkbox? I've seen these all work:
<input name="checkbox_name" id="checkbox_id" type="checkbox" checked>
<input name="checkbox_name" id="checkbox_id" type="checkbox" checked="on">
<input name="checkbox_name" id="checkbox_id" type="checkbox" checked="yes">
<input name="checkbox_name" id="checkbox_id" type="checkbox" checked="checked">
<input name="checkbox_name" id="checkbox_id" type="checkbox" checked="true">
Is the answer that it doesn't matter? I see no evidence for the answer marked as correct here from the spec itself:
Checkboxes (and radio buttons) are on/off switches that may be toggled
by the user. A switch is "on" when the control element's checked
attribute is set. When a form is submitted, only "on" checkbox
controls can become successful. Several checkboxes in a form may share
the same control name. Thus, for example, checkboxes allow users to
select several values for the same property. The INPUT element is used
to create a checkbox control.
What would a spec writer say is the correct answer? Please provide evidence-based answers.
Strictly speaking, you should put something that makes sense - according to the spec here, the most correct version is:
<input name=name id=id type=checkbox checked=checked>
For HTML, you can also use the empty attribute syntax, checked="", or even simply checked (for stricter XHTML, this is not supported).
Effectively, however, most browsers will support just about any value between the quotes. All of the following will be checked:
<input name=name id=id type=checkbox checked>
<input name=name id=id type=checkbox checked="">
<input name=name id=id type=checkbox checked="yes">
<input name=name id=id type=checkbox checked="blue">
<input name=name id=id type=checkbox checked="false">
And only the following will be unchecked:
<input name=name id=id type=checkbox>
See also this similar question on disabled="disabled".
HTML5 spec:
http://www.w3.org/TR/html5/forms.html#attr-input-checked :
The disabled content attribute is a boolean attribute.
http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.
Conclusion:
The following are valid, equivalent and true:
<input type="checkbox" checked />
<input type="checkbox" checked="" />
<input type="checkbox" checked="checked" />
<input type="checkbox" checked="ChEcKeD" />
The following are invalid:
<input type="checkbox" checked="0" />
<input type="checkbox" checked="1" />
<input type="checkbox" checked="false" />
<input type="checkbox" checked="true" />
The absence of the attribute is the only valid syntax for false:
<input />
Recommendation
If you care about writing valid XHTML, use checked="checked", since <input checked> is invalid XHTML (but valid HTML) and other alternatives are less readable. Else, just use <input checked> as it is shorter.
<input ... checked />
<input ... checked="checked" />
Those are equally valid. And in JavaScript:
input.checked = true;
input.setAttribute("checked");
input.setAttribute("checked","checked");
you want this i think:
checked='checked'
checked
checked=""
checked="checked"
are equivalent;
according to spec checkbox
'----ⓘ checked = "checked" or "" (empty string) or empty
Specifies that the element represents a selected control.---'
It's pretty crazy town that the only way to make checked false is to omit any values. With Angular 1.x, you can do this:
<input type="radio" ng-checked="false">
which is a lot more sane, if you need to make it unchecked.
I think this may help:
First read all the specs from Microsoft and W3.org.
You'd see that the setting the actual element of a checkbox needs to be done on the ELEMENT PROPERTY, not the UI or attribute.
$('mycheckbox')[0].checked
Secondly, you need to be aware that the checked attribute RETURNS a string "true", "false"Why is this important? Because you need to use the correct Type. A string, not a boolean. This also important when parsing your checkbox.
$('mycheckbox')[0].checked = "true"
if($('mycheckbox')[0].checked === "true"){
//do something
}
You also need to realize that the "checked" ATTRIBUTE is for setting the value of the checkbox initially. This doesn't do much once the element is rendered to the DOM. Picture this working when the webpage loads and is initially parsed.
I'll go with IE's preference on this one: <input type="checkbox" checked="checked"/>
Lastly, the main aspect of confusion for a checkbox is that the checkbox UI element is not the same as the element's property value. They do not correlate directly.
If you work in .net, you'll discover that the user "checking" a checkbox never reflects the actual bool value passed to the controller.
To set the UI, I use both $('mycheckbox').val(true); and $('mycheckbox').attr('checked', 'checked');
In short, for a checked checkbox you need:
Initial DOM: <input type="checkbox" checked="checked">
Element Property: $('mycheckbox')[0].checked = "true";
UI: $('mycheckbox').val(true); and $('mycheckbox').attr('checked', 'checked');
Just like all input's, this one also has a 'value' attribute. If you set the value attribute along with the name attribute, it will send ${name}=${value} in the headers. Let's say we had a form with a bunch of stuff and we wanted the user to decide what roles they have, we could use a checkbox. The easiest way is to set the 'value' attribute which will be passed along to the server. Like this:
<form action="/server" method="post">
<label>Are you a person?</label>
<input type="checkbox" name="my_checkbox" value="is_person">
</form>
The server will receive the following:
my_checkbox=is_person
but only if the checkbox is checked. This would be
my_checkbox=
if it is empty.
This is the exact same with radio inputs.
But.. I have a feeling this isn't what you're asking for... So just encase I'll write another answer below:
If the checked attribute is set to anything (even false) it will be activated, no matter what. The checked attribute doesn't have a specified value, if it's set to anything it will default to 'true' (even if you set it to false).
For example:
<form action="/server" method="post">
<label>Are you a person?</label>
<input type="checkbox" checked="false"> <!--Still checked-->
</form>
Will be checked even though it's set to false.
<form action="/server" method="post">
<label>Are you a person?</label>
<input type="checkbox" checked="asjdiasjiasdjoasi"> <!--Still checked-->
</form>
Doing this will also check it. It doesn't matter -- as long as it's set it will be checked.
Hope this answers your question, the checked attribute will check the input no matter the value of the attribute.
You can test it here: https://battledash-2.github.io/Live-IDE/
or anywhere like repl.it, or locally.
The technically correct value for a checked checkbox is zero (0), and when the checkbox is not checked, it's index is not defined.
Well, to use it i dont think matters (similar to disabled and readonly), personally i use checked="checked" but if you are trying to manipulate them with JavaScript, you use true/false

Can HTML checkboxes be set to readonly?

I thought they could be, but as I'm not putting my money where my mouth was (so to speak) setting the readonly attribute doesn't actually seem to do anything.
I'd rather not use Disabled, since I want the checked check boxes to be submitted with the rest of the form, I just don't want the client to be able to change them under certain circumstances.
you can use this:
<input type="checkbox" onclick="return false;"/>
This works because returning false from the click event stops the chain of execution continuing.
READONLY doesn't work on checkboxes as it prevents you from editing a field's value, but with a checkbox you're actually editing the field's state (on || off)
From faqs.org:
It's important to understand that READONLY merely prevents the user from changing the value of the field, not from interacting with the field. In checkboxes, for example, you can check them on or off (thus setting the CHECKED state) but you don't change the value of the field.
If you don't want to use disabled but still want to submit the value, how about submitting the value as a hidden field and just printing its contents to the user when they don't meet the edit criteria? e.g.
// user allowed change
if($user_allowed_edit)
{
echo '<input type="checkbox" name="my_check"> Check value';
}
else
{
// Not allowed change - submit value..
echo '<input type="hidden" name="my_check" value="1" />';
// .. and show user the value being submitted
echo '<input type="checkbox" disabled readonly> Check value';
}
This is a checkbox you can't change:
<input type="checkbox" disabled="disabled" checked="checked">
Just add disabled="disabled" as an attribute.
Edit to address the comments:
If you want the data to be posted back, than a simple solutions is to apply the same name to a hidden input:
<input name="myvalue" type="checkbox" disabled="disabled" checked="checked"/>
<input name="myvalue" type="hidden" value="true"/>
This way, when the checkbox is set to 'disabled', it only serves the purpose of a visual representation of the data, instead of actually being 'linked' to the data. In the post back, the value of the hidden input is being sent when the checkbox is disabled.
<input type="checkbox" onclick="this.checked=!this.checked;">
But you absolutely MUST validate the data on the server to ensure it hasn't been changed.
another "simple solution":
<!-- field that holds the data -->
<input type="hidden" name="my_name" value="1" />
<!-- visual dummy for the user -->
<input type="checkbox" name="my_name_visual_dummy" value="1" checked="checked" disabled="disabled" />
disabled="disabled" / disabled=true
This presents a bit of a usability issue.
If you want to display a checkbox, but not let it be interacted with, why even a checkbox then?
However, my approach would be to use disabled (The user expects a disabled checkbox to not be editable, instead of using JS to make an enabled one not work), and add a form submit handler using javascript that enables checkboxes right before the form is submitted. This way you you do get your values posted.
ie something like this:
var form = document.getElementById('yourform');
form.onSubmit = function ()
{
var formElems = document.getElementsByTagName('INPUT');
for (var i = 0; i , formElems.length; i++)
{
if (formElems[i].type == 'checkbox')
{
formElems[i].disabled = false;
}
}
}
<input type="checkbox" readonly="readonly" name="..." />
with jquery:
$(':checkbox[readonly]').click(function(){
return false;
});
it still might be a good idea to give some visual hint (css, text,...), that the control won't accept inputs.
I would use the readonly attribute
<input type="checkbox" readonly>
Then use CSS to disable interactions:
input[type='checkbox'][readonly]{
pointer-events: none;
}
Note that using the pseudo-class :read-only doesn't work here.
input[type='checkbox']:read-only{ /*not working*/
pointer-events: none;
}
Belated answer, but most answers seem to over complicate it.
As I understand it, the OP was basically wanting:
Readonly checkbox to show status.
Value returned with form.
It should be noted that:
The OP preferred not to use the disabled attribute, because they 'want the checked check boxes to be submitted with the rest of the form'.
Unchecked checkboxes are not submitted with the form, as the quote from the OP in 1. above indicates they knew already. Basically, the value of the checkbox only exists if it is checked.
A disabled checkbox clearly indicates that it cannot be changed, by design, so a user is unlikely to attempt to change it.
The value of a checkbox is not limited to indicating its status, such as yes or false, but can be any text.
Therefore, since the readonly attribute does not work, the best solution, requiring no javascript, is:
A disabled checkbox, with no name or value.
If the checkbox is to be displayed as checked, a hidden field with the name and value as stored on the server.
So for a checked checkbox:
<input type="checkbox" checked="checked" disabled="disabled" />
<input type="hidden" name="fieldname" value="fieldvalue" />
For an unchecked checkbox:
<input type="checkbox" disabled="disabled" />
The main problem with disabled inputs, especially checkboxes, is their poor contrast which may be a problem for some with certain visual disabilities. It may be better to indicate a value by plain words, such as Status: none or Status: implemented, but including the hidden input above when the latter is used, such as:
<p>Status: Implemented<input type="hidden" name="status" value="implemented" /></p>
I used this to achieve the results:
<input type=checkbox onclick="return false;" onkeydown="return false;" />
Most of the current answers have one or more of these problems:
Only check for mouse not keyboard.
Check only on page load.
Hook the ever-popular change or submit events which won't always work out if something else has them hooked.
Require a hidden input or other special elements/attributes that you have to undo in order to re-enable the checkbox using javascript.
The following is simple and has none of those problems.
$('input[type="checkbox"]').on('click keyup keypress keydown', function (event) {
if($(this).is('[readonly]')) { return false; }
});
If the checkbox is readonly, it won't change. If it's not, it will. It does use jquery, but you're probably using that already...
It works.
I happened to notice the solution given below. In found it my research for the same issue.
I don't who had posted it but it wasn't made by me. It uses jQuery:
$(document).ready(function() {
$(":checkbox").bind("click", false);
});
This would make the checkboxes read only which would be helpful for showing readonly data to the client.
onclick="javascript: return false;"
If you want them to be submitted to the server with form but be not interacive for user, you can use pointer-events: none in css (works in all modern browsers except IE10- and Opera 12-) and set tab-index to -1 to prevent changing via keyboard. Also note that you can't use label tag as click on it will change the state anyway.
input[type="checkbox"][readonly] {
pointer-events: none !important;
}
td {
min-width: 5em;
text-align: center;
}
td:last-child {
text-align: left;
}
<table>
<tr>
<th>usual
<th>readonly
<th>disabled
</tr><tr>
<td><input type=checkbox />
<td><input type=checkbox readonly tabindex=-1 />
<td><input type=checkbox disabled />
<td>works
</tr><tr>
<td><input type=checkbox checked />
<td><input type=checkbox readonly checked tabindex=-1 />
<td><input type=checkbox disabled checked />
<td>also works
</tr><tr>
<td><label><input type=checkbox checked /></label>
<td><label><input type=checkbox readonly checked tabindex=-1 /></label>
<td><label><input type=checkbox disabled checked /></label>
<td>broken - don't use label tag
</tr>
</table>
<input name="isActive" id="isActive" type="checkbox" value="1" checked="checked" onclick="return false"/>
<input type="checkbox" onclick="return false" /> will work for you , I am using this
Some of the answers on here seem a bit roundabout, but here's a small hack.
<form id="aform" name="aform" method="POST">
<input name="chkBox_1" type="checkbox" checked value="1" disabled="disabled" />
<input id="submitBttn" type="button" value="Submit" onClick='return submitPage();'>
</form>​
then in jquery you can either choose one of two options:
$(document).ready(function(){
//first option, you don't need the disabled attribute, this will prevent
//the user from changing the checkbox values
$("input[name^='chkBox_1']").click(function(e){
e.preventDefault();
});
//second option, keep the disabled attribute, and disable it upon submit
$("#submitBttn").click(function(){
$("input[name^='chkBox_1']").attr("disabled",false);
$("#aform").submit();
});
});
​
demo:
http://jsfiddle.net/5WFYt/
Building on the above answers, if using jQuery, this may be an good solution for all inputs:
<script>
$(function () {
$('.readonly input').attr('readonly', 'readonly');
$('.readonly textarea').attr('readonly', 'readonly');
$('.readonly input:checkbox').click(function(){return false;});
$('.readonly input:checkbox').keydown(function () { return false; });
});
</script>
I'm using this with Asp.Net MVC to set some form elements read only. The above works for text and check boxes by setting any parent container as .readonly such as the following scenarios:
<div class="editor-field readonly">
<input id="Date" name="Date" type="datetime" value="11/29/2012 4:01:06 PM" />
</div>
<fieldset class="flags-editor readonly">
<input checked="checked" class="flags-editor" id="Flag1" name="Flags" type="checkbox" value="Flag1" />
</fieldset>
<input type="radio" name="alwaysOn" onchange="this.checked=true" checked="checked">
<input type="radio" name="alwaysOff" onchange="this.checked=false" >
I know that "disabled" isn't an acceptable answer, since the op wants it to post. However, you're always going to have to validate values on the server side EVEN if you have the readonly option set. This is because you can't stop a malicious user from posting values using the readonly attribute.
I suggest storing the original value (server side), and setting it to disabled. Then, when they submit the form, ignore any values posted and take the original values that you stored.
It'll look and behave like it's a readonly value. And it handles (ignores) posts from malicious users. You're killing 2 birds with one stone.
No, input checkboxes can't be readonly.
But you can make them readonly with javascript!
Add this code anywhere at any time to make checkboxes readonly work as assumed, by preventing the user from modifying it in any way.
jQuery(document).on('click', function(e){
// check for type, avoid selecting the element for performance
if(e.target.type == 'checkbox') {
var el = jQuery(e.target);
if(el.prop('readonly')) {
// prevent it from changing state
e.preventDefault();
}
}
});
input[type=checkbox][readonly] {
cursor: not-allowed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" checked readonly> I'm readonly!</label>
You can add this script at any time after jQuery has loaded.
It will work for dynamically added elements.
It works by picking up the click event (that happens before the change event) on any element on the page, it then checks if this element is a readonly checkbox, and if it is, then it blocks the change.
There are so many ifs to make it not affect the performance of the page.
readonly does not work with <input type='checkbox'>
So, if you need to submit values from disabled checkboxes in a form, you can use jQuery:
$('form').submit(function(e) {
$('input[type="checkbox"]:disabled').each(function(e) {
$(this).removeAttr('disabled');
})
});
This way the disabled attributes are removed from the elements when submitting the form.
I would have commented on ConroyP's answer, but that requires 50 reputation which I don't have. I do have enough reputation to post another answer. Sorry.
The problem with ConroyP's answer is that the checkbox is rendered unchangeable by not even including it on the page. Although Electrons_Ahoy does not stipulate as much, the best answer would be one in which the unchangeable checkbox would look similar, if not the same as, the changeable checkbox, as is the case when the "disabled" attribute is applied. A solution which addresses the two reasons Electrons_Ahoy gives for not wanting to use the "disabled" attribute would not necessarily be invalid because it utilized the "disabled" attribute.
Assume two boolean variables, $checked and $disabled :
if ($checked && $disabled)
echo '<input type="hidden" name="my_name" value="1" />';
echo '<input type="checkbox" name="my_name" value="1" ',
$checked ? 'checked="checked" ' : '',
$disabled ? 'disabled="disabled" ' : '', '/>';
The checkbox is displayed as checked if $checked is true. The checkbox is displayed as unchecked if $checked is false. The user can change the state of the checkbox if and only if $disabled is false. The "my_name" parameter is not posted when the checkbox is unchecked, by the user or not. The "my_name=1" parameter is posted when the checkbox is checked, by the user or not. I believe this is what Electrons_Ahoy was looking for.
If you want ALL your checkboxes to be "locked" so user can't change the "checked" state if "readonly" attibute is present, then you can use jQuery:
$(':checkbox').click(function () {
if (typeof ($(this).attr('readonly')) != "undefined") {
return false;
}
});
Cool thing about this code is that it allows you to change the "readonly" attribute all over your code without having to rebind every checkbox.
It works for radio buttons as well.
This works for me on Chrome:
<input type="checkbox" onclick="return false">
Very late to the party but I found an answer for MVC (5)
I disabled the CheckBox and added a HiddenFor BEFORE the checkbox, so when it is posting if finds the Hidden field first and uses that value. This does work.
<div class="form-group">
#Html.LabelFor(model => model.Carrier.Exists, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.HiddenFor(model => model.Carrier.Exists)
#Html.CheckBoxFor(model => model.Carrier.Exists, new { #disabled = "disabled" })
#Html.ValidationMessageFor(model => model.Carrier.Exists)
</div>
</div>
I just don't want the client to be able to change them under certain circumstances.
READONLY itself won't work. You may be able to do something funky w/CSS but we usually just make them disabled.
WARNING: If they're posted back then the client can change them, period. You can't rely on readonly to prevent a user from changing something. The could always use fiddler or just chane the html w/firebug or some such thing.
The main reason people would like a read-only check-box and (as well) a read-only radio-group is so that information that cannot be changed can be presented back to the user in the form it was entered.
OK disabled will do this -- unfortunately disabled controls are not keyboard navigable and therefore fall foul of all accessibility legislation. This is the BIGGEST hangup in HTML that I know of.
Contributing very very late...but anyway. On page load, use jquery to disable all checkboxes except the currently selected one. Then set the currently selected one as read only so it has a similar look as the disabled ones. User cannot change the value, and the selected value still submits.
If you need the checkbox to be submitted with the form but effectively read-only to the user, I recommend setting them to disabled and using javascript to re-enable them when the form is submitted.
This is for two reasons. First and most important, your users benefit from seeing a visible difference between checkboxes they can change and checkboxes which are read-only. Disabled does this.
Second reason is that the disabled state is built into the browser so you need less code to execute when the user clicks on something. This is probably more of a personal preference than anything else. You'll still need some javascript to un-disable these when submitting the form.
It seems easier to me to use some javascript when the form is submitted to un-disable the checkboxes than to use a hidden input to carry the value.