How can I make a checkbox readonly? not disabled? - javascript

I have a form where I have to post form values to my action class. In this form I have a checkbox that needs to be readonly. I tried setting disabled="true" but that doesn't work when posting to the action class.
So please advice??

There is no property to make the checkbox readonly. But you can try this trick.
<input type="checkbox" onclick="return false" />
DEMO

<input type="checkbox" checked onclick="return false;" onkeydown="return false;"/>
http://jsfiddle.net/2srjc/
If you are worried about tab order, only return false for the keydown event when the tab key was not pressed:
<input type="checkbox" checked onclick="return false;" onkeydown="e = e || window.event; if(e.keyCode !== 9) return false;"/>
http://jsfiddle.net/2srjc/149/

You can easily do this by css.
HTML :
<form id="aform" name="aform" method="POST">
<input name="chkBox_1" type="checkbox" checked value="1" readonly />
<br/>
<input name="chkBox_2" type="checkbox" value="1" readonly />
<br/>
<input id="submitBttn" type="button" value="Submit">
</form>
CSS :
input[type="checkbox"][readonly] {
pointer-events: none;
}
Demo

I personally like to do it this way:
<input type="checkbox" name="option" value="1" disabled="disabled" />
<input type="hidden" name="option" value="1">
I think this is better for two reasons:
User clearly understand that he can't edit this value
The value is sent when submitting the form.

You may simply add onclick="return false" - this will stop browser executing default action (checkbox checked/not checked will not be changed)

Make a fake checkbox with no name and value, force the value in an hidden field:
<input type="checkbox" disabled="disabled" checked="checked">
<input type="hidden" name="name" value="true">
Note: if you put name and value in the checkbox, it will be anyway overwritten by the input with the same name

I use JQuery so I can use the readonly attribute on checkboxes.
//This will make all read-only check boxes truly read-only
$('input[type="checkbox"][readonly]').on("click.readonly", function(event){event.preventDefault();}).css("opacity", "0.5");
If you want the checkbox to be editable again then you need to do the following for the specific checkbox.
$('specific checkbox').off('.readonly').removeAttr("readonly").css("opacity", "1")

If you say 'No' to the following:
disable=true because other functionalities may not work, such as form posting.
onclick='return false' because other events may still trigger the
change, such as keyup, keydown when on focus.
e.preventDefault()
CSS: pointer-events: none; because you may want to allow change
under certain conditions.
Then just do this in the change event of your read-only checkbox:
$("#chkReadOnly").on("change", function () {
// Enclose with 'if' statement if conditional.
// Simply restore back the default value, i.e. true.
$(this).prop("checked", true);
});
This will solve all the above problems.

None of the above worked for me. Here's my vanilla.js solution:
(function() {
function handleSubmit(event) {
var form = event.target;
var nodes = form.querySelectorAll("input[disabled]");
for (var node of nodes) {
node.disabled = false;
}
}
function init() {
var submit_form_tag = document.getElementById('new_whatever');
submit_form_tag.addEventListener('submit', handleSubmit, true);
}
window.onload = init_beworst;
})();
Be sure to provide an appropriate replacement for the form id.
My application has a bit of context, where some boxes are pre-checked, and others you have a limit of how many of the other boxes you can check. When you hit that limit, all the non-pre-checked boxes are disabled, and if you uncheck one all the non-pre-checked boxes are enabled again. When the user presses submit all the checked boxes are submitted to the user, regardless of whether they're pre-checked or not.

In my case, i only needed it within certain conditions, and to be done easily in HTML:
<input type="checkbox" [style.pointer-events]="(condition == true) ? 'none' : 'auto'">
Or in case you need this consistently:
<input type="checkbox" style="pointer-events: none;">

You can't do it directly, but you can do it with this way I try it, and it's work fine with me at the same time it is so simple
HTML :
<input type="checkbox" checked disabled="true" class="style" />
CSS :
.style{ opacity: 1; }

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;
}
}
});

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="checkbox"]:not(:checked)').prop('disabled',true);
// and, on the selected ones, to deactivate mouse/keyboard events and mimic readonly appearance
$('#' + idElement + ' input[type="checkbox"]:checked').prop('tabindex','-1').css('pointer-events','none').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="checkbox"]:not(:checked)').prop('disabled',false);
// Restore mouse/keyboard events and remove readonly appearance on selected ones
$('#' + idElement + ' input[type="checkbox"]:checked').prop('tabindex','').css('pointer-events','').css('opacity','');
}

Through CSS:
<label for="">
<input type="checkbox" style="pointer-events: none; tabindex: -1;" checked> Label
</label>
pointer-events not supported in IE<10
https://jsfiddle.net/fl4sh/3r0v8pug/2/

document.getElementById("your checkbox id").disabled=true;

Related

Enable or disable target element based on checkbox checked state

i'm basically JavaScript newbie and I'm trying to resolve this problem of mine for quite a while. So,i'm doing JS school project and I need to make connection between checkbox and text form. If checkbox is not checked, text form should be disabled and vice versa. This is piece of code I have written:
function cbtf() {
if (document.getElementById('checkbox').checked==false) {
document.getElementById('textform').disabled=true;
}
}
Can anyone write a new code ? That would be much of a help.
Simply attach a method to checkbox's onclick handler:
function enableElement(id, enable) {
document.getElementById(id).disabled=!enable;
}
<label>
<input
type="checkbox"
onclick="enableElement('textform', this.checked)"
/>
ENABLE
</label>
<br/>
<textarea id="textform" style="width:100%; height:200px" disabled>
THIS IS TEXTAREA WITH ID "textform"
</textarea>
or another simplification without creating special one-liner method - just define Your will directy in onclick event:
<label>
<input
type="checkbox"
onclick="document.getElementById('textform').disabled = !this.checked"
/>
ENABLE
</label>
<br/>
<textarea id="textform" style="width:100%; height:200px" disabled>
THIS IS TEXTAREA WITH ID "textform"
</textarea>
You can add a click event to the checkbox, and assign it's check state to the disabled property of the TextBox.
document.querySelector('input[type=checkbox]').onclick = function(e) {
document.querySelector('input[type=text]').disabled = e.target.checked;
};
<input type="checkbox" name="">
<input type="text" name="">
You won't get that to work unless you attach an event to the checkbox, so I would suggest something like this:
var textbox = document.getElementById('textform');
var checkbox = document.getElementById('checkbox');
checkbox.addEventListener("change", function() {
if (checkbox.checked) {
textbox.disabled = false;
} else {
textbox.disabled = true;
}
})

jQuery disable textbox input for type number

I have a HTML markup which looks like following:
<input type="number" step="0.1" min="0" max="100" value="1" class="form-control breakEvenInput" style="width:150px" /><br />
<button type="submit" class="btn btn-primary saveBreakEven">Save</button>
As you can see the input is of type "number"... What I was thinking (if it's possible) to do here is to disable the end user so that he/she is not able to input anything into the textbox, but rather enable the user just to have that side scrool up/down arrows that he gets when browser renders the HTML input as type of "number".
I've tried to add "disabled" or "readonly" properties to HTML input but that didn't give me the desired result. When I do it like that then the entire textbox is disabled...
I was thinking that this might be done somehow via jQuery? Can someone help me out ?
P.S. So i'd like to disable the input into the textbox via keyboard, but still leave the up/down arrows in textbox for the user to change the value, so that the user can't enter anything they want , let's say 99999999999 number.. ?
One of the things you can do is to prevent the keydown event.
$(function() {
$('input').on('keydown', function(e) {
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" step="0.1" min="0" max="100" value="1" class="form-control breakEvenInput" style="width:150px" /><br />
<button type="submit" class="btn btn-primary saveBreakEven">Save</button>
This way you keep the arrows active, but disable keyboard keys.
Inside the event object (e), you can also check what key was pressed (if you want to support backspace or arrows for example).
An issue you will have is different browsers support and render type="number" differently. I would suggest a span element for the number readout (ff you need to have it as an input, I would hide it), and use styled buttons or elements to increase, decrease the number and update the input box. This will give a uniform user experience across browsers.
<!--style these how you want-->
<span id="number">0</span>
<button id="add>Up</button><button id="sub">Down</button>
<script>
var step = 1;
var output = $('#number');
var up = $('#add');
var sub = $('#sub');
up.add(sub).on('click', function() {
var num = output.val();
num += ( $(this).attr('id') == 'add' ) ? step : (-1 * step);
if( isNumValid(num) ) {
output.val(num);
} else { <!-- error reporting here --> }
}
function isNumValid(num) {
<!-- run validations here, integer, float, positive, etc -->
return true/false;
}
</script>
$(function() {
$('input[type=number]').on('keydown', function(e){
e.preventDefault();
});
});

How to hide radio button until something happens?

So I want to hide a radio button until my form is filled out but I don't know how. I tried .hide(); and that worked when I put it outside of my .submit function but doesn't work inside of it. This is using jquery and bootstrap.
Here is a small version of the JS I have ('agree' is the radio button):
$('myForm').submit(function(e){
var firstName = $('first-name').val();
var pattern = /^$/;
var error = '';
var checkbox = document.getElementById('agree');
if(pattern.test(firstName)){
error += 'Error: enter first name.\n';
}
if(error.length != 0){
alert(error);
e.preventDefault();
}
});
I want to hide the radio button until the first name part of the form is filled out then the radio button will appear.
Put an id in your radio like this :
<input type="radio" id="rad" />
Then hide it like this using jquery :
$('#rad').hide();
Then an example of how you can make it show when something happens would go a bit like this :
If ($('#something') > 10) {
$('#rad').show();
}
Hope this helped :)
I would use plain JavaScript for this:
<input type="text" name="first-name" value="" onchange="document.getElementById('agree').style.display = (this.value == '' ? 'block' : 'none' );"/>
<input type="checkbox" name="agree" value="Agree" style="display:none"/>
Edit:
Other ways to do this is to use onkeydown, onkeyup or onblur instead of onchange
Here is a simple example using jquery... http://jsfiddle.net/wa8rxj43/2/
HTML
<input type="text" id="name" class="name">
<input class="not-display" id="somecheck" type="checkbox" name="vehicle" value="Car" checked>
JavaScript
$('#somecheck').hide();
$("#name").bind({
'input':function(){
if(this.value.length > 0)
{
$('#somecheck').show();
}
else
{
$('#somecheck').hide();
}
}
});
Edit: Removed CSS per OP's request.

javascript confirm when checking a checkbox by clicking on the label

I have a checkbox on a form that does something dangerous. So, I want to make sure the user is really sure when they check this item, but I don't want to warn them if they're unchecking the checkbox.
My issue is this works fine if they click on the actual checkbox to uncheck it, but not the text of the label.
http://jsfiddle.net/j2ppzpdk/
function askApply() {
if (document.getElementById("apply").checked) {
var answer = confirm("Are you sure about that?");
if (!answer) {
document.getElementById("apply").checked = false;
}
}
}
<form>
<label onclick="askApply();">
<input type="checkbox" name="apply" id="apply" value="1" /> Apply
</label>
</form>
Some notes:
Better add the event listener to the element that changes (the checkbox), not its label.
Better listen to change event instead of click. For example, the checkbox could be changed using the keyboard.
Better avoid inline event listeners. You can use addEventListener instead.
document.getElementById('apply').addEventListener('change', function() {
if(this.checked) {
var answer = confirm("Are you sure about that?");
if (!answer) {
document.getElementById("apply").checked = false;
}
}
});
<form>
<label>
<input type="checkbox" name="apply" id="apply" value="1" />
Apply
</label>
</form>

Enable checkbox if text field is not empty with inconsistent id

Purpose is to have checkboxes disabled when the page loads, and remain greyed out until textbox is filled.
<input type="text" name="<%=commentID%>" />
<input type="checkbox" name="<%=SkipID%>" value="N" disabled/>
I tried to do something like
<input type="text" name="<%=commentID%>" onkeyup="userTyped('<%=SkipID%>') />
function userTyped(commen){
if(this.value.length > 0){
document.getElementById(commen).disabled=false;
}else{
document.getElementById(commen).disabled=true;
}
}
But it did not work. I am assuming because of the inconsistency of the name, but I have to have that.
You haven't given id to your html elements and is trying to use getElementById, which will return null. Javascript engine will not be able to set disabled attribute of null. Try setting id attribute, for elements as given below.
Also in your userTyped function you are referencing this. this here is the window object and not the input element. You need to pass the reference to input element to make this work, like this onkeyup="userTyped('<%=SkipID%>', this)"
Please find a possible correction below:
<input type="text" name="<%=commentID%>" id="<%=commentID%>" onkeyup="userTyped('<%=SkipID%>', this)" />
<input type="checkbox" name="<%=SkipID%>" id="<%=SkipID%>" value="N" disabled/>
/** commen is the id
* e is the input element
**/
function userTyped(commen, e){
if(e.value.length > 0){
document.getElementById(commen).disabled=false;
}else{
document.getElementById(commen).disabled=true;
}
}
jsFiddle here: http://jsfiddle.net/deepumohanp/dGS9H/

Categories