Can HTML checkboxes be set to readonly? - html

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.

Related

How to disable Chrome autofill (after 2020)

I've stumbled across this issue a couple of times in the last while, where Chrome ignores autocomplete="false" and autocomplete="off". It will now even ignore autocomplete="whatever" or anything you do to trick it, if someone has submitted a form with that random "hack" in it before.
In trying to solve this issue, I came across this StackOverflow question, which doesn't solve the problem if you've submitted a form containing this field before.
EDIT: This is NOT for password fields.
I had this issue with a field that has "number" in the name and this triggering the CreditCard Autocomplete Dialog. This solution helped me get rid of it.
Even though this is not the intended use of the option, I think this is unlikely to break and works without JavaScript Hacks. A one time code won't trigger an autocomplete so I treat the fields that are not supposed to autocomplete as one time codes.
<input type="text" name="number" autocomplete="one-time-code" />
This did the trick for me. I tested it in Chrome 87.0.4280.141 and it works fine.
autocomplete="new-password" and set placeholder attribute with some text works for me.
<input name="name1" placeholder="Nº" type="text" autocomplete="new-password" />
Everytime I found a solution Chrome throws a spanner in the works again.
No longer working
autocomplete="new-*"
add an offscreen positioned bogus input element style="position: fixed;top:-100px;left:-100px;" as first <form> element
set <form autocomplete="off">
use <textarea> and style it as a field
Working solution (15 jul 2021)
Append a dummy <input> without a name attribute and make the original <input> type="hidden"
HTML
<input type="hidden" name="myfield" class="no-autofill"> <input>
Note that any events, (click, blur, focus) that show your custom
autofill should be added to the visible <input> element.
Then add a change event to sync the value to the hidden input.
const fields = document.querySelectorAll('input.no-autofill');
for (const field of fields) {
const dummy = field.nextElementSibling;
dummy.addEventListener('change',e => {
field.value = e.target.value;
});
}
Ow, before implementing. Make sure you visit the Chromium bug tracker
and tell the Chrome Developers why following the standard is important. So one day we might be able to just use:
<input name="myfield" autocomplete="off">
its work in my local machine try it...
<input type="email" class="form-control" id="email" name="email" placeholder="Enter Email" readonly onfocus="this.removeAttribute('readonly');" style="background-color: white;">
It's November 2021, and none of the non-javascript solutions mentioned worked for my address-related field. What did work was actually changing the text in the label.
The Autocomplete dialog in Chrome was shown if:
The word "Address" is in the label at the start or end; and
There are at least two other address fields (seemingly anywhere in the page)
EDIT: If you put a zero-width joiner character entity in the middle of the word 'Address' in the label, the autocomplete dialog is suppressed!
i.e. set the label to Addres‍s
html, body {
font-family: 'Helvetica', Sans-Serif;
font-weight: 200;
line-height: 1.5em;
padding: 1em;
}
<div class="addressDiv">
<div>
<label>Focus on this field...Address</label>
<div>
<input autocomplete="off" type="text" aria-autocomplete="none" autocapitalize="none" />
</div>
</div>
<div>
<label>State</label>
<div>
<input autocomplete="address-level1" type="text" value="">
</div>
</div>
<div>
<label>City</label>
<div>
<input autocomplete="address-level2" type="text" value="">
</div>
</div>
</div>
<p>
See this JSFiddle
</p>
Read the note at the bottom before using this method
After struggling for a long time, I made it work reliably this way:
It is important that your input type is 'text'!!
define a css class
input.hidden-password {
-webkit-text-security: disc;
}
Then in your form, set autocomplete off, input types = 'text' and add the class to the input.
<form autocomplete="off">
<input
type = "text" // <----This is important
class = "hidden-password"
/>
</form>
C'mon Google, let us take control over our inputs! My client requires passwords to be changed very often and auto fill IS A BIG NO NO!
IMPORTANT NOTE Do not use this for login or any other place where security is required. I used this for a form within my app where the user was already authenticated and security was not required.
For Me, the problem only occurs, if I have multiple fields with the same value for autocomplete. If I set the value to a random number (Math.random()), no autocomplete is happening. I think it would also be possible to use an otherwise unique string.
To prevent 'manage addresses' level of of chrome popup: autocomplete='chrome-off'
To prevent autosuggest popup, if you can swing it: EXCLUDE name and id attributes.
Try to make your input readonly, enable it after focus
<input readonly="readonly" onfocus="this.removeAttribute('readonly');" type="text" value="test">
here is JS solution that works at this point in time for me:
<input name="name" type="text"
onfocus="this.__name = this.getAttribute('name'); this.removeAttribute('name')"
onblur="this.setAttribute('name',this.__name)"
>
The above js code stores input name to this.__name and removes the name onfocus later onblur name is restored so forms can work as expected, but chrome does not autofill.
No known attribute value is working in form tag. I have tried them all: do-not-show-ac, chrome-off, new-password, off...
The only way i found is by adding autocomplete='new-password' to every input component. To do it globaly, i am using this jquery:
<script>
$('input').attr('autocomplete', 'new-password');
</script>
The best way is to use JavaScript to skip browser's behavior, disableautofill.js does this.
You can try https://github.com/terrylinooo/disableautofill.js
<script src="https://cdn.jsdelivr.net/npm/disableautofill#2.0.0/dist/disableautofill.min.js"></script>
Usage:
var daf = new disableautofill({
'form': '#testForm', // Form id
'fields': [
'.test-pass', // password
'.test-pass2' // confirm password
],
'debug': true,
'callback': function() {
return checkForm(); // Form validator
}
});
daf.init();
How about just never submit the form? Nothing to remember!
Your app probably doesn't work without javascript anyway, right?
In fact, don't use a form at all, just collect the input values, serialize and do an ajax call.
$('#mybutton').on('click', function (e) {
$.ajax({
type: "POST",
url: 'mybackend',
data: $('#formdiv input').serialize(),
success: function (data) ...
Mind you, this is not a well tested idea, just something I have observed when I wanted autofill, and which I have not seen suggested in any of the many threads dealing with this issue.
I just resolved a related issue - it was forcing Chrome Autofill on an address field (Google Places Autocomplete, specifically) and no other solutions were working.
Eventually, we changed the nearest label to it from saying "Business Address" to being blank and set its text via CSS
#gmapsSearchLabel:after {
content: "Business Address";
}
And without a nearby label "saying" address, it stopped forcing Autofill.
A solution that works for me is to place a zero-width-white-space character into the placeholder text, so for example:
placeholder="Enter your address" becomes
placeholder="Enter your a[ZWSP]ddress"
Chrome is then unable to find "address" and skips autocomplete suggestions.
You can copy the character ( don't use the html entity etc. ) over at CSS Tricks. Here is the word "address" with the ZWSP character after the letter "a":
a​ddress
Dirty answer ,
edit "selectorForYourInputs" and works just fine, cross browser tested, max overhead 50ms, user never notice any performance lag:
counter = 0;
emptySearchboxInterval = setInterval(() => {
$(selectorForYourInputs).val("");
counter++;
counter == 100 ? clearInterval(emptySearchboxInterval) : null;
}, 20);

html5 "required" attribute for mixed radio/text

I'm designing a form which has, among others, the following elements:
<div>
<div class="radio-list">
<label><input type="radio" name="ftp_directory" id="ftpdir_public_html" value="public_html"> <strong>public_html</strong> directory</label>
<label><input type="radio" name="ftp_directory" id="ftpdir_blank" value="."> <strong>Root</strong> directory </label>
<label><input type="radio" id="ftpdir_custom" value=""> Other directory (please specify)</label>
</div>
<input name="ftp_directory" class="form-control" type="text" disabled="disabled" aria-disabled="true">
</div>
I enable the latter <input> text element when I check the 3rd radio (via jQuery) and all is fine.
What I want to do is set up the required attribute in a correct way so that it vaildates if any of the first two radio button is checked or the 3rd radio is checked and the input has some text.
Note: I know I can do it with some JS/jQuery validation code but I'd like to do it in pure HTML5.
As already said, you cannot do this with radio buttons + text input. However, you can achieve something similar with data lists and a single text field:
<input type="text" name="ftp_directory" list="preselection" required>
<datalist id="preselection">
<option>public_html</option>
<option value=".">current directory</option>
</datalist>
Logically, this meets exactly your constraints. However, it might not be stylistically what you're looking for.
I solved via jQuery, as said it is not possible with HTML5 only.
Here's my solution:
$(document).on('change', 'input[type="radio"][name="ftp_directory"]', function(e){
var radio_id = $(this).attr('id');
if (radio_id == 'ftpdir_custom')
{
$('#ftp_directory_custom').prop('disabled', false);
$('#ftp_directory_custom').prop('required', true);
$('input[type="radio"][name="ftp_directory"]').removeProp('required').removeAttr('aria-required');
}
else
{
$('#ftp_directory_custom').prop('disabled', true);
$('#ftp_directory_custom').removeProp('required');
$('input[type="radio"][name="ftp_directory"]').prop('required', true);
}
});
The name attribute must be different, anyway, for radio buttons and text input. Plus, because of the latter, one has to detect and differentiate request parameters server-side accordingly.
Improvements are welcome.

An invalid form control with name='' is not focusable

In Google Chrome some customers are not able to proceed to my payment page.
When trying to submit a form I get this error:
An invalid form control with name='' is not focusable.
This is from the JavaScript console.
I read that the problem could be due to hidden fields having the required attribute.
Now the problem is that we are using .net webforms required field validators, and not the html5 required attribute.
It seems random who gets this error.
Is there anyone who knows a solution for this?
This issue occurs on Chrome if a form field fails validation, but due to the respective invalid control not being focusable the browser's attempt to display the message "Please fill out this field" next to it fails as well.
A form control may not be focusable at the time validation is triggered for several reasons. The two scenarios described below are the most prominent causes:
The field is irrelevant according to the current context of the business logic. In such a scenario, the respective control should be disabled or removed from the DOM or not be marked with the required attribute at that point.
Premature validation may occur due to a user pressing ENTER key on an input. Or a user clicking on a button/input control in the form which has not defined the type attribute of the control correctly. If the type attribute of a button is not set to button, Chrome (or any other browser for that matter) performs a validation each time the button is clicked because submit is the default value of a button's type attribute.
To solve the problem, if you have a button on your page that does something else other than submit or reset, always remember to do this: <button type="button">.
Adding a novalidate attribute to the form will help:
<form name="myform" novalidate>
In your form, You might have hidden input having required attribute:
<input type="hidden" required />
<input type="file" required style="display: none;"/>
The form can't focus on those elements, you have to remove required from all hidden inputs, or implement a validation function in javascript to handle them if you really require a hidden input.
In case anyone else has this issue, I experienced the same thing. As discussed in the comments, it was due to the browser attempting to validate hidden fields. It was finding empty fields in the form and trying to focus on them, but because they were set to display:none;, it couldn't. Hence the error.
I was able to solve it by using something similar to this:
$("body").on("submit", ".myForm", function(evt) {
// Disable things that we don't want to validate.
$(["input:hidden, textarea:hidden, select:hidden"]).attr("disabled", true);
// If HTML5 Validation is available let it run. Otherwise prevent default.
if (this.el.checkValidity && !this.el.checkValidity()) {
// Re-enable things that we previously disabled.
$(["input:hidden, textarea:hidden, select:hidden"]).attr("disabled", false);
return true;
}
evt.preventDefault();
// Re-enable things that we previously disabled.
$(["input:hidden, textarea:hidden, select:hidden"]).attr("disabled", false);
// Whatever other form processing stuff goes here.
});
Also, this is possibly a duplicate of "Invalid form control" only in Google Chrome
In my case the problem was with the input type="radio" required being hidden with:
visibility: hidden;
This error message will also show if the required input type radio or checkbox has a display: none; CSS property.
If you want to create custom radio/checkbox inputs where they must be hidden from the UI and still keep the required attribute, you should instead use the:
opacity: 0; CSS property
None of the previous answers worked for me, and I don't have any hidden fields with the required attribute.
In my case, the problem was caused by having a <form> and then a <fieldset> as its first child, which holds the <input> with the required attribute. Removing the <fieldset> solved the problem. Or you can wrap your form with it; it is allowed by HTML5.
I'm on Windows 7 x64, Chrome version 43.0.2357.130 m.
Not only required field as mentioned in other answers. Its also caused by placing an <input> field in a hidden <div> which holds an invalid value.
Consider below example,
<div style="display:none;">
<input type="number" name="some" min="1" max="50" value="0">
</div>
This throws the same error. So make sure the <input> fields inside hidden <div> doesnt hold any invalid value.
This issue occurs when you provide style="display: none;" and required attribute to the input field, and there will be validation on submit.
for example:
<input type="text" name="name" id="name" style="display: none;" required>
This issue can be resolved by removing required attribute from the input field from your HTML. If you need to add required attribute, add it dynamically. If you are using JQuery, use below code:
$("input").prop('required',true);
If you need to remove this field dynamically,
$("input").prop('required',false);
You can also make use of plain Javascript if you are not using JQuery:
document.getElementById('element_id').removeAttribute('required');
Yet another possibility if you're getting the error on a checkbox input. If your checkboxes use custom CSS which hides the default and replaces it with some other styling, this will also trigger the not focusable error in Chrome on validation error.
I found this in my stylesheet:
input[type="checkbox"] {
visibility: hidden;
}
Simple fix was to replace it with this:
input[type="checkbox"] {
opacity: 0;
}
It can be that you have hidden (display: none) fields with the required attribute.
Please check all required fields are visible to the user :)
For me this happens, when there's a <select> field with pre-selected option with value of '':
<select name="foo" required="required">
<option value="" selected="selected">Select something</option>
<option value="bar">Bar</option>
<option value="baz">Baz</option>
</select>
Unfortunately it's the only cross-browser solution for a placeholder (How do I make a placeholder for a 'select' box?).
The issue comes up on Chrome 43.0.2357.124.
For Select2 Jquery problem
The problem is due to the HTML5 validation cannot focus a hidden invalid element.
I came across this issue when I was dealing with jQuery Select2 plugin.
Solution
You could inject an event listener on and 'invalid' event of every element of a form so that you can manipulate just before the HTML5 validate event.
$('form select').each(function(i){
this.addEventListener('invalid', function(e){
var _s2Id = 's2id_'+e.target.id; //s2 autosuggest html ul li element id
var _posS2 = $('#'+_s2Id).position();
//get the current position of respective select2
$('#'+_s2Id+' ul').addClass('_invalid'); //add this class with border:1px solid red;
//this will reposition the hidden select2 just behind the actual select2 autosuggest field with z-index = -1
$('#'+e.target.id).attr('style','display:block !important;position:absolute;z-index:-1;top:'+(_posS2.top-$('#'+_s2Id).outerHeight()-24)+'px;left:'+(_posS2.left-($('#'+_s2Id).width()/2))+'px;');
/*
//Adjust the left and top position accordingly
*/
//remove invalid class after 3 seconds
setTimeout(function(){
$('#'+_s2Id+' ul').removeClass('_invalid');
},3000);
return true;
}, false);
});
If you have any field with required attribute which is not visible during the form submission, this error will be thrown. You just remove the required attribute when your try to hide that field. You can add the required attribute in case if you want to show the field again. By this way, your validation will not be compromised and at the same time, the error will not be thrown.
It's weird how everyone is suggesting to remove the validation, while validation exists for a reason...
Anyways, here's what you can do if you're using a custom control, and want to maintain the validation:
1st step. Remove display none from the input, so the input becomes focusable
.input[required], .textarea[required] {
display: inline-block !important;
height: 0 !important;
padding: 0 !important;
border: 0 !important;
z-index: -1 !important;
position: absolute !important;
}
2nd step. Add invalid event handler on the input to for specific cases if the style isn't enough
inputEl.addEventListener('invalid', function(e){
//if it's valid, cancel the event
if(e.target.value) {
e.preventDefault();
}
});
It happens if you hide an input element which has a required attribute.
Instead of using display:none you can use opacity: 0;
I also had to use some CSS rules (like position:absolute) to position my element perfectly.
Yea.. If a hidden form control has required field then it shows this error. One solution would be to disable this form control. This is because usually if you are hiding a form control it is because you are not concerned with its value. So this form control name value pair wont be sent while submitting the form.
I came here to answer that I had triggered this issue myself based on NOT closing the </form> tag AND having multiple forms on the same page. The first form will extend to include seeking validation on form inputs from elsewhere. Because THOSE forms are hidden, they triggered the error.
so for instance:
<form method="POST" name='register' action="#handler">
<input type="email" name="email"/>
<input type="text" name="message" />
<input type="date" name="date" />
<form method="POST" name='register' action="#register">
<input type="text" name="userId" />
<input type="password" name="password" />
<input type="password" name="confirm" />
</form>
Triggers
An invalid form control with name='userId' is not focusable.
An invalid form control with name='password' is not focusable.
An invalid form control with name='confirm' is not focusable.
Another possible cause and not covered in all previous answers when you have a normal form with required fields and you submit the form then hide it directly after submission (with javascript) giving no time for validation functionality to work.
The validation functionality will try to focus on the required field and show the error validation message but the field has already been hidden, so "An invalid form control with name='' is not focusable." appears!
Edit:
To handle this case simply add the following condition inside your submit handler
submitHandler() {
const form = document.body.querySelector('#formId');
// Fix issue with html5 validation
if (form.checkValidity && !form.checkValidity()) {
return;
}
// Submit and hide form safely
}
Edit: Explanation
Supposing you're hiding the form on submission, this code guarantees that the form/fields will not be hidden until form become valid. So, if a field is not valid, the browser can focus on it with no problems as this field is still displayed.
There are many ways to fix this like
Add novalidate to your form but its totally wrong as it will remove form validation which will lead to wrong information entered by the users.
<form action="...." class="payment-details" method="post" novalidate>
Use can remove the required attribute from required fields which is also wrong as it will remove form validation once again.
Instead of this:
<input class="form-control" id="id_line1" maxlength="255" name="line1" placeholder="First line of address" type="text" required="required">
Use this:
<input class="form-control" id="id_line1" maxlength="255" name="line1" placeholder="First line of address" type="text">
Use can disable the required fields when you are not going to submit the form instead of doing some other option. This is the recommended solution in my opinion.
like:
<input class="form-control" id="id_line1" maxlength="255" name="line1" placeholder="First line of address" type="text" disabled="disabled">
or disable it through javascript / jquery code dependes upon your scenario.
It will show that message if you have code like this:
<form>
<div style="display: none;">
<input name="test" type="text" required/>
</div>
<input type="submit"/>
</form>
You may try .removeAttribute("required") for those elements which are hidden at the time of window load. as it is quite probable that the element in question is marked hidden due to javascript (tabbed forms)
e.g.
if(document.getElementById('hidden_field_choice_selector_parent_element'.value==true){
document.getElementById('hidden_field').removeAttribute("required");
}
This should do the task.
It worked for me... cheers
There are things that still surprises me... I have a form with dynamic behaviour for two different entities. One entity requires some fields that the other don't.
So, my JS code, depending on the entity, does something like:
$('#periodo').removeAttr('required');
$("#periodo-container").hide();
and when the user selects the other entity:
$("#periodo-container").show();
$('#periodo').prop('required', true);
But sometimes, when the form is submitted, the issue apppears: "An invalid form control with name=periodo'' is not focusable (i am using the same value for the id and name).
To fix this problem, you have to ensurance that the input where you are setting or removing 'required' is always visible.
So, what I did is:
$("#periodo-container").show(); //for making sure it is visible
$('#periodo').removeAttr('required');
$("#periodo-container").hide(); //then hide
Thats solved my problem... unbelievable.
In my case..
ng-show was being used.
ng-if was put in its place and fixed my error.
Wow, a lot of answers here!
If the problem is <input type="hidden" required="true" />, then you can solve this in just a few lines.
The logic is simple and straight-forward:
Mark every required input on page-load with a data-required class.
On submit, do two things: a) Add required="true" to all data-required inputs. b) Remove required="true"` from all hidden inputs.
HTML
<input type="submit" id="submit-button">
Pure JavaScript
document.querySelector('input,textarea,select').filter('[required]').classList.add('data-required');
document.querySelector('#submit-button').addEventListener('click', function(event) {
document.querySelector('.data-required').prop('required', true);
document.querySelector('input,textarea,select').filter('[required]:hidden').prop('required', false);
return true;
}
jQuery
$('input,textarea,select').filter('[required]').addClass('data-required');
$('#submit-button').on('click', function(event) {
$('.data-required').prop('required', true);
$('input,textarea,select').filter('[required]:hidden').prop('required', false);
return true;
}
For Angular use:
ng-required="boolean"
This will only apply the html5 'required' attribute if the value is true.
<input ng-model="myCtrl.item" ng-required="myCtrl.items > 0" />
I found same problem when using Angular JS. It was caused from using required together with ng-hide. When I clicked on the submit button while this element was hidden then it occurred the error An invalid form control with name='' is not focusable. finally!
For example of using ng-hide together with required:
<input type="text" ng-hide="for some condition" required something >
I solved it by replacing the required with ng-pattern instead.
For example of solution:
<input type="text" ng-hide="for some condition" ng-pattern="some thing" >
Not just only when specify required, I also got this issue when using min and max e.g.
<input type="number" min="1900" max="2090" />
That field can be hidden and shown based on other radio value. So, for temporary solution, I removed the validation.
I have seen this question asked often and have come across this 'error' myself. There have even been links to question whether this is an actual bug in Chrome.
This is the response that occurs when one or more form input type elements are hidden and these elements have a min/max limit (or some other validation limitation) imposed.
On creation of a form, there are no values attributed to the elements, later on the element values may be filled or remain unchanged.
At the time of submit, the form is parsed and any hidden elements that are outside of these validation limits will throw this 'error' into the console and the submit will fail. Since you can't access these elements (because they are hidden) this is the only response that is valid.
This isn't an actual fault nor bug. It is an indication that there are element values about to be submitted that are outside of the limits stipulated by one or more elements.
To fix this, assign a valid default value to any elements that are hidden in the form at any time before the form is submitted, then these 'errors' will never occur. It is not a bug as such, it is just forcing you into better programming habits.
NB: If you wish to set these values to something outside the validation limits then use form.addEventListener('submit', myFunction) to intercept the 'submit' event and fill in these elements in "myFunction". It seems the validation checking is performed before "myFunction() is called.
Its because there is a hidden input with required attribute in the form.
In my case, I had a select box and it is hidden by jquery tokenizer using inline style. If I dont select any token, browser throws the above error on form submission.
So, I fixed it using the below css technique :
select.download_tag{
display: block !important;//because otherwise, its throwing error An invalid form control with name='download_tag[0][]' is not focusable.
//So, instead set opacity
opacity: 0;
height: 0px;
}
For other AngularJS 1.x users out there, this error appeared because I was hiding a form control from displaying instead of removing it from the DOM entirely when I didn't need the control to be completed.
I fixed this by using ng-if instead of ng-show/ng-hide on the div containing the form control requiring validation.
Hope this helps you fellow edge case users.

Why is the HTML form input attribute "readonly" only supported for input and textarea elements? [duplicate]

I would like to show a radio button, have its value submitted, but depending on the circumstances, have it not editable. Disabled doesn't work, because it doesn't submit the value (or does it?), and it grays out the radio button. Read-only is really what I'm looking for, but for some mysterious reason it doesn't work.
Is there some weird trick I need to pull to get read-only to work as expected? Should I just do it in JavaScript instead?
Incidentally, does anyone know why read-only doesn't work in radio buttons, while it does work in other input tags? Is this one of those incomprehensible omissions in the HTML specs?
Radio buttons would only need to be read-only if there are other options. If you don't have any other options, a checked radio button cannot be unchecked. If you have other options, you can prevent the user from changing the value merely by disabling the other options:
<input type="radio" name="foo" value="Y" checked>
<input type="radio" name="foo" value="N" disabled>
Fiddle: http://jsfiddle.net/qqVGu/
I've faked readonly on a radio button by disabling only the un-checked radio buttons. It keeps the user from selecting a different value, and the checked value will always post on submit.
Using jQuery to make readonly:
$(':radio:not(:checked)').attr('disabled', true);
This approach also worked for making a select list readonly, except that you'll need to disable each un-selected option.
This is the trick you can go with.
<input type="radio" name="name" onclick="this.checked = false;" />
I have a lengthy form (250+ fields) that posts to a db. It is an online employment application. When an admin goes to look at an application that has been filed, the form is populated with data from the db. Input texts and textareas are replaced with the text they submitted but the radios and checkboxes are useful to keep as form elements. Disabling them makes them harder to read. Setting the .checked property to false onclick won't work because they may have been checked by the user filling out the app. Anyhow...
onclick="return false;"
works like a charm for 'disabling' radios and checkboxes ipso facto.
The best solution is to set the checked or unchecked state (either from client or server) and to not let the user change it after wards (i.e make it readonly) do the following:
<input type="radio" name="name" onclick="javascript: return false;" />
I've come up with a javascript-heavy way to achieve a readonly state for check boxes and radio buttons. It is tested against current versions of Firefox, Opera, Safari, Google Chrome, as well as current and previous versions of IE (down to IE7).
Why not simply use the disabled property you ask? When printing the page, disabled input elements come out in a gray color. The customer for which this was implemented wanted all elements to come out the same color.
I'm not sure if I'm allowed to post the source code here, as I developed this while working for a company, but I can surely share the concepts.
With onmousedown events, you can read the selection state before the click action changes it. So you store this information and then restore these states with an onclick event.
<input id="r1" type="radio" name="group1" value="r1" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);" checked="checked">Option 1</input>
<input id="r2" type="radio" name="group1" value="r2" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);">Option 2</input>
<input id="r3" type="radio" name="group1" value="r3" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);">Option 3</input>
<input id="c1" type="checkbox" name="group2" value="c1" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);" checked="checked">Option 1</input>
<input id="c2" type="checkbox" name="group2" value="c2" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);">Option 2</input>
<input id="c3" type="checkbox" name="group2" value="c3" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);" checked="checked">Option 3</input>
The javascript portion of this would then work like this (again only the concepts):
var selectionStore = new Object(); // keep the currently selected items' ids in a store
function storeSelectedRadiosForThisGroup(elementName) {
// get all the elements for this group
var radioOrSelectGroup = document.getElementsByName(elementName);
// iterate over the group to find the selected values and store the selected ids in the selectionStore
// ((radioOrSelectGroup[i].checked == true) tells you that)
// remember checkbox groups can have multiple checked items, so you you might need an array for the ids
...
}
function setSelectedStateForEachElementOfThisGroup(elementName) {
// iterate over the group and set the elements checked property to true/false, depending on whether their id is in the selectionStore
...
// make sure you return false here
return false;
}
You can now enable/disable the radio buttons/checkboxes by changing the onclick and onmousedown properties of the input elements.
For the non-selected radio buttons, flag them as disabled. This prevents them from responding to user input and clearing out the checked radio button. For example:
<input type="radio" name="var" checked="yes" value="Yes"></input>
<input type="radio" name="var" disabled="yes" value="No"></input>
JavaScript way - this worked for me.
<script>
$(document).ready(function() {
$('#YourTableId').find('*').each(function () { $(this).attr("disabled", true); });
});
</script>
Reason:
$('#YourTableId').find('*') -> this returns all the tags.
$('#YourTableId').find('*').each(function () { $(this).attr("disabled", true); });
iterates over all objects captured in this and disable input tags.
Analysis (Debugging):
form:radiobutton is internally considered as an "input" tag.
Like in the above function(), if you try printing document.write(this.tagName);
Wherever, in tags it finds radio buttons, it returns an input tag.
So, above code line can be more optimized for radio button tags, by replacing * with input:
$('#YourTableId').find('input').each(function () { $(this).attr("disabled", true); });
A fairly simple option would be to create a javascript function called on the form's "onsubmit" event to enable the radiobutton back so that it's value is posted with the rest of the form.
It does not seem to be an omission on HTML specs, but a design choice (a logical one, IMHO), a radiobutton can't be readonly as a button can't be, if you don't want to use it, then disable it.
I found that use onclick='this.checked = false;' worked to a certain extent. A radio button that was clicked would not be selected. However, if there was a radio button that was already selected (e.g., a default value), that radio button would become unselected.
<!-- didn't completely work -->
<input type="radio" name="r1" id="r1" value="N" checked="checked" onclick='this.checked = false;'>N</input>
<input type="radio" name="r1" id="r1" value="Y" onclick='this.checked = false;'>Y</input>
For this scenario, leaving the default value alone and disabling the other radio button(s) preserves the already selected radio button and prevents it from being unselected.
<!-- preserves pre-selected value -->
<input type="radio" name="r1" id="r1" value="N" checked="checked">N</input>
<input type="radio" name="r1" id="r1" value="Y" disabled>Y</input>
This solution is not the most elegant way of preventing the default value from being changed, but it will work whether or not javascript is enabled.
Try the attribute disabled, but I think the you won't get the value of the radio buttons.
Or set images instead like:
<img src="itischecked.gif" alt="[x]" />radio button option
Best Regards.
I'm using a JS plugin that styles checkbox/radio input elements and used the following jQuery to establish a 'readonly state' where the underlying value is still posted but the input element appears inaccessible to the user, which is I believe the intended reason we would use a readonly input attribute...
if ($(node).prop('readonly')) {
$(node).parent('div').addClass('disabled'); // just styling, appears greyed out
$(node).on('click', function (e) {
e.preventDefault();
});
}
Here is my solution (override) for Sencha ExtJS 7.2+ (checkbox and radio in a single override)
Ext.define('MyApp.override.field.Checkbox', {
override: 'Ext.field.Checkbox',
/**
* OVERRIDE: to allow updateReadOnly to work propperly
* #param {boolean} newValue
*
* To ensure the disabled state stays active if the field is still readOnly
* we re - set the disabled state
*/
updateDisabled(newValue) {
this.callParent(arguments);
if (!newValue && this.getReadOnly()) {
this.inputElement.dom.disabled = true;
}
},
/**
* OVERRIDE: readonly for radiogroups and checkboxgroup do not work as other fields
* https://stackoverflow.com/questions/1953017/why-cant-radio-buttons-be-readonly
*
* #param {boolean} newValue
*
* - use disabled on the field
*/
updateReadOnly(value) {
this.callParent(arguments);
if (!this.getDisabled()) {
this.inputElement.dom.disabled = value;
}
}
});
Disabled works on individual radio buttons (not the whole set).
If you are using PHP and your circumstances are known on the server before loading the page in the browser you can use this very simple solution.
<php $chcky= (condition) ? 'checked' : 'disabled';?>
<php $chckn= (condition) ? 'checked' : 'disabled';?>
<input type="radio" name="var" value="Yes" <?php echo $chcky?>></input>
<input type="radio" name="var" value="No" <?php echo $chckn?>></input>
I use it on the page responding a form submission.
Extract from https://stackoverflow.com/a/71086058/18183749
If you can't use the 'disabled' attribut (as it erases the value's
input at POST), and noticed that html attribut 'readonly' works only
on textarea and some input(text, password, search, as far I've seen),
and finally, if you don't want to bother with duplicating all your
select, checkbox and radio with hidden input, you might find the
following function or any of his inner logics to your liking :
addReadOnlyToFormElements = function (idElement) {
// html readonly don't work on input of type checkbox and radio, neither on select. So, a safe trick is to disable the non-selected items
$('#' + idElement + ' input[type="radio"]:not(:checked)').prop('disabled',true);
// and, on the selected ones, mimic readonly appearance
$('#' + idElement + ' input[type="radio"]:checked').css('opacity','0.5');
}
And there's nothing easier than to remove these readonly
removeReadOnlyFromFormElements = function (idElement) {
// Remove the disabled attribut on non-selected
$('#' + idElement + ' input[type="radio"]:not(:checked)').prop('disabled',false);
// Remove readonly appearance on selected ones
$('#' + idElement + ' input[type="radio"]:checked').css('opacity','');
}
What about capturing an "On_click()" event in JS and checking it like here?:
http://www.dynamicdrive.com/forums/showthread.php?t=33043

Why can't radio buttons be "readonly"?

I would like to show a radio button, have its value submitted, but depending on the circumstances, have it not editable. Disabled doesn't work, because it doesn't submit the value (or does it?), and it grays out the radio button. Read-only is really what I'm looking for, but for some mysterious reason it doesn't work.
Is there some weird trick I need to pull to get read-only to work as expected? Should I just do it in JavaScript instead?
Incidentally, does anyone know why read-only doesn't work in radio buttons, while it does work in other input tags? Is this one of those incomprehensible omissions in the HTML specs?
Radio buttons would only need to be read-only if there are other options. If you don't have any other options, a checked radio button cannot be unchecked. If you have other options, you can prevent the user from changing the value merely by disabling the other options:
<input type="radio" name="foo" value="Y" checked>
<input type="radio" name="foo" value="N" disabled>
Fiddle: http://jsfiddle.net/qqVGu/
I've faked readonly on a radio button by disabling only the un-checked radio buttons. It keeps the user from selecting a different value, and the checked value will always post on submit.
Using jQuery to make readonly:
$(':radio:not(:checked)').attr('disabled', true);
This approach also worked for making a select list readonly, except that you'll need to disable each un-selected option.
This is the trick you can go with.
<input type="radio" name="name" onclick="this.checked = false;" />
I have a lengthy form (250+ fields) that posts to a db. It is an online employment application. When an admin goes to look at an application that has been filed, the form is populated with data from the db. Input texts and textareas are replaced with the text they submitted but the radios and checkboxes are useful to keep as form elements. Disabling them makes them harder to read. Setting the .checked property to false onclick won't work because they may have been checked by the user filling out the app. Anyhow...
onclick="return false;"
works like a charm for 'disabling' radios and checkboxes ipso facto.
The best solution is to set the checked or unchecked state (either from client or server) and to not let the user change it after wards (i.e make it readonly) do the following:
<input type="radio" name="name" onclick="javascript: return false;" />
I've come up with a javascript-heavy way to achieve a readonly state for check boxes and radio buttons. It is tested against current versions of Firefox, Opera, Safari, Google Chrome, as well as current and previous versions of IE (down to IE7).
Why not simply use the disabled property you ask? When printing the page, disabled input elements come out in a gray color. The customer for which this was implemented wanted all elements to come out the same color.
I'm not sure if I'm allowed to post the source code here, as I developed this while working for a company, but I can surely share the concepts.
With onmousedown events, you can read the selection state before the click action changes it. So you store this information and then restore these states with an onclick event.
<input id="r1" type="radio" name="group1" value="r1" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);" checked="checked">Option 1</input>
<input id="r2" type="radio" name="group1" value="r2" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);">Option 2</input>
<input id="r3" type="radio" name="group1" value="r3" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);">Option 3</input>
<input id="c1" type="checkbox" name="group2" value="c1" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);" checked="checked">Option 1</input>
<input id="c2" type="checkbox" name="group2" value="c2" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);">Option 2</input>
<input id="c3" type="checkbox" name="group2" value="c3" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);" checked="checked">Option 3</input>
The javascript portion of this would then work like this (again only the concepts):
var selectionStore = new Object(); // keep the currently selected items' ids in a store
function storeSelectedRadiosForThisGroup(elementName) {
// get all the elements for this group
var radioOrSelectGroup = document.getElementsByName(elementName);
// iterate over the group to find the selected values and store the selected ids in the selectionStore
// ((radioOrSelectGroup[i].checked == true) tells you that)
// remember checkbox groups can have multiple checked items, so you you might need an array for the ids
...
}
function setSelectedStateForEachElementOfThisGroup(elementName) {
// iterate over the group and set the elements checked property to true/false, depending on whether their id is in the selectionStore
...
// make sure you return false here
return false;
}
You can now enable/disable the radio buttons/checkboxes by changing the onclick and onmousedown properties of the input elements.
For the non-selected radio buttons, flag them as disabled. This prevents them from responding to user input and clearing out the checked radio button. For example:
<input type="radio" name="var" checked="yes" value="Yes"></input>
<input type="radio" name="var" disabled="yes" value="No"></input>
JavaScript way - this worked for me.
<script>
$(document).ready(function() {
$('#YourTableId').find('*').each(function () { $(this).attr("disabled", true); });
});
</script>
Reason:
$('#YourTableId').find('*') -> this returns all the tags.
$('#YourTableId').find('*').each(function () { $(this).attr("disabled", true); });
iterates over all objects captured in this and disable input tags.
Analysis (Debugging):
form:radiobutton is internally considered as an "input" tag.
Like in the above function(), if you try printing document.write(this.tagName);
Wherever, in tags it finds radio buttons, it returns an input tag.
So, above code line can be more optimized for radio button tags, by replacing * with input:
$('#YourTableId').find('input').each(function () { $(this).attr("disabled", true); });
A fairly simple option would be to create a javascript function called on the form's "onsubmit" event to enable the radiobutton back so that it's value is posted with the rest of the form.
It does not seem to be an omission on HTML specs, but a design choice (a logical one, IMHO), a radiobutton can't be readonly as a button can't be, if you don't want to use it, then disable it.
I found that use onclick='this.checked = false;' worked to a certain extent. A radio button that was clicked would not be selected. However, if there was a radio button that was already selected (e.g., a default value), that radio button would become unselected.
<!-- didn't completely work -->
<input type="radio" name="r1" id="r1" value="N" checked="checked" onclick='this.checked = false;'>N</input>
<input type="radio" name="r1" id="r1" value="Y" onclick='this.checked = false;'>Y</input>
For this scenario, leaving the default value alone and disabling the other radio button(s) preserves the already selected radio button and prevents it from being unselected.
<!-- preserves pre-selected value -->
<input type="radio" name="r1" id="r1" value="N" checked="checked">N</input>
<input type="radio" name="r1" id="r1" value="Y" disabled>Y</input>
This solution is not the most elegant way of preventing the default value from being changed, but it will work whether or not javascript is enabled.
Try the attribute disabled, but I think the you won't get the value of the radio buttons.
Or set images instead like:
<img src="itischecked.gif" alt="[x]" />radio button option
Best Regards.
I'm using a JS plugin that styles checkbox/radio input elements and used the following jQuery to establish a 'readonly state' where the underlying value is still posted but the input element appears inaccessible to the user, which is I believe the intended reason we would use a readonly input attribute...
if ($(node).prop('readonly')) {
$(node).parent('div').addClass('disabled'); // just styling, appears greyed out
$(node).on('click', function (e) {
e.preventDefault();
});
}
Here is my solution (override) for Sencha ExtJS 7.2+ (checkbox and radio in a single override)
Ext.define('MyApp.override.field.Checkbox', {
override: 'Ext.field.Checkbox',
/**
* OVERRIDE: to allow updateReadOnly to work propperly
* #param {boolean} newValue
*
* To ensure the disabled state stays active if the field is still readOnly
* we re - set the disabled state
*/
updateDisabled(newValue) {
this.callParent(arguments);
if (!newValue && this.getReadOnly()) {
this.inputElement.dom.disabled = true;
}
},
/**
* OVERRIDE: readonly for radiogroups and checkboxgroup do not work as other fields
* https://stackoverflow.com/questions/1953017/why-cant-radio-buttons-be-readonly
*
* #param {boolean} newValue
*
* - use disabled on the field
*/
updateReadOnly(value) {
this.callParent(arguments);
if (!this.getDisabled()) {
this.inputElement.dom.disabled = value;
}
}
});
Disabled works on individual radio buttons (not the whole set).
If you are using PHP and your circumstances are known on the server before loading the page in the browser you can use this very simple solution.
<php $chcky= (condition) ? 'checked' : 'disabled';?>
<php $chckn= (condition) ? 'checked' : 'disabled';?>
<input type="radio" name="var" value="Yes" <?php echo $chcky?>></input>
<input type="radio" name="var" value="No" <?php echo $chckn?>></input>
I use it on the page responding a form submission.
Extract from https://stackoverflow.com/a/71086058/18183749
If you can't use the 'disabled' attribut (as it erases the value's
input at POST), and noticed that html attribut 'readonly' works only
on textarea and some input(text, password, search, as far I've seen),
and finally, if you don't want to bother with duplicating all your
select, checkbox and radio with hidden input, you might find the
following function or any of his inner logics to your liking :
addReadOnlyToFormElements = function (idElement) {
// html readonly don't work on input of type checkbox and radio, neither on select. So, a safe trick is to disable the non-selected items
$('#' + idElement + ' input[type="radio"]:not(:checked)').prop('disabled',true);
// and, on the selected ones, mimic readonly appearance
$('#' + idElement + ' input[type="radio"]:checked').css('opacity','0.5');
}
And there's nothing easier than to remove these readonly
removeReadOnlyFromFormElements = function (idElement) {
// Remove the disabled attribut on non-selected
$('#' + idElement + ' input[type="radio"]:not(:checked)').prop('disabled',false);
// Remove readonly appearance on selected ones
$('#' + idElement + ' input[type="radio"]:checked').css('opacity','');
}
What about capturing an "On_click()" event in JS and checking it like here?:
http://www.dynamicdrive.com/forums/showthread.php?t=33043