Knockout attr binding with attributes like 'readonly' and 'disabled' - html

What's the suggested "best practice" way to use Knockout's "attr" data binding with standalone attributes like "readonly" and "disabled"?
These attributes are special in that they are generally enabled by setting the attribute value to the attribute name (although many browsers work fine if you simply include the attribute names without any values in the HTML):
<input type="text" readonly="readonly" disabled="disabled" value="foo" />
However, if you don't want these attributes to be applied, the general practice is to simply omit them altogether from the HTML (as opposed to doing something like readonly="false"):
<input type="text" value="foo" />
Knockout's "attr" data binding doesn't support this scenario. As soon as I provide an attribute name, I need to provide a value as well:
<input type="text" data-bind="attr: { 'disabled': getDisabledState() }" />
Is there a cross-browser way turn off 'disabled' or 'readonly'? Or is there a trick with a custom binding that I can use to not render anything if I don't want the item disabled or made read-only?

Knockout's "attr" data binding does support this scenario just return null or undefined from your getDisabledState() function then it won't emit the attribute.
Demo Fiddle.

You can also create a binding for readonly like this:
ko.bindingHandlers['readonly'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (!value && element.readOnly)
element.readOnly = false;
else if (value && !element.readOnly)
element.readOnly = true;
}
};
Source: https://github.com/knockout/knockout/issues/1100

Knockout has an enable binding as well as a disable binding.
I'm not sure if these were available when the question was asked, but anyone referring back to this issue should be aware.

Related

Add key to React Tag dynamically

Have been looking for this answer in SO, but perhaps I'm not frasing it correctly or there is actually no answer yet for this.
I am using an input component that uses a key to render it valid (green border) or invalid (red border) and I would like to add it dynamically:
<Input type="select" valid /> //This input has green border
<Input type="select" invalid /> //This input has red border
Since they key valid/invalid has no value like true or false, I'm not sure how to change it dynamically through a function since as far as I'm aware, I can change values dynamically with a JSX expression, but not add a key itself.
Can you please suggest a way to add 'valid' or 'invalid' tag dynamically without value?
"Without value" is actually not accurate. What you see there is syntactic sugar for valid={true} and invalid={true}.
So, the same can be accomplished by:
const valid = // whatever logic here to determine if it's valid.
<Input type="select" valid={valid} invalid={!valid} /> // Either return or assign to something.
Alternatively:
let inputProps = {type: 'select'};
if (/* whatever logic here to determine if it's valid*/) {
inputProps.valid = true;
}
else {
inputProps.invalid = true;
}
<Input {...inputProps} />; // Either return or assign to something.
But the latter is a lot more verbose.
Not sure if this will work but give it a try.
JSX reads properties without values/= as boolean/true.
Set null values:
<Input type="select" invalid={null} />
You can then conditionally show valid or invalid input elements

Explicitly set disabled="false" in the HTML does not work

I would like to explicitly set a button as enabled in the html file. The reason is that my code later on toggles the button to disabled and if the code crashes or so I might see the button disabled.
I can disable the button with
$("#btn").attr("disabled","true")
but then an html containing:
<button id="btn" disabled="false">I want to be enabled!</button>
still shows the button as disabled.
The inspector shows:
<button id="btn" disabled="">I want to be enabled!</button>
I know I can do
$("#btn").removeAttr("disabled")
or similar, but it is not convenient to do that for many elements in the html.
HTML doesn't use boolean values for boolean attributes, surprisingly.
In HTML, boolean attributes are specified by either merely adding the attribute name, or (especially in XHTML) by using the attribute name as its value.
<input type="checkbox" disabled> <!-- HTML -->
<input type="checkbox" disabled /> <!-- Also HTML -->
<input type="checkbox" disabled="disabled" /> <!-- XHTML and HTML -->
This is documented in the HTML specification: http://www.w3.org/TR/html5/infrastructure.html#boolean-attribute
A number of attributes are 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.
The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.
To add to the confusion, in the DOM these boolean attributes are specified with boolean values, for example:
/** #type HTMLInputElement */
const inputElement = document.createElement('input');
inputElement.disabled = true; // <-- The DOM *does* use a proper boolean value here.
console.log( inputElement.disabled ); // Prints "true"
inputElement.disabled = false;
console.log( inputElement.disabled ); // Prints "false"
...to add even more confusion - due to JavaScript's falsyness - using string values with the property will not work as you'd expect:
inputElement.disabled = 'true';
console.log( inputElement.disabled ); // Prints "true"
inputElement.disabled = 'false';
console.log( inputElement.disabled ); // *Still* prints "true"
(This is because the JavaScript string 'false' is not type-coerced into the JavaScript boolean value false).
Also, some HTML attributes do have true and false as possible values, such as contentEditable (which also has inherit as a third option), also consider <form autocomplete=""> which can be on and off (and many other values), which might trip some people up too. I think some legacy (Internet Explorer 4.0-era) extensions like <object> and <applet> may have had boolean attributes, and definitely had booleans in their child <param value=""> attributes, that's just an historical curiosity at this point).
In future, can help someone.
selectLanguage.onchange = function() {
var value = selectLanguage.value;
if (value != '') {
submitLanguage.removeAttr('disabled');
} else {
submitLanguage.attr('disabled', 'disabled');
}
// submitLanguage.attr('enabled', 'enabled');
}
I know this is an old topic but as there is no marked answer, does this help? This does answer the explicitly marked as enabled question.
<button enabled>My Text</button>
<!-- Which also works as: -->
<button enabled="enabled">My Text</button>
I too am investigating this for use to enabled a button when validation occurs. I hope this helps someone.
If you are using AngularJS, try ng-disabled instead. In this case you can use stuff like:
ng-disabled="true"
ng-disabled="false"
ng-disabled={{expression}}
and it works as expected....
You have to use element.removeAttribute("disabled");
Thanks
In 2022 if you're using EJS or Vue, you should be setting it as:
EJS:
<div <%=true?'enabled':'disabled'%> ></div>
Vue:
<div :disabled="someFuncInMethods()"></div>

Input field set as 'Value=' instead of 'value='

I have a project written in C# MVC using Razor templates. On one of my pages I have several input fields that contain numeric values. The Razor code that sets the values of these input fields looks like this:
#Html.Editor(Model.DesignParams[i].ParamId,
new {
htmlAttributes = new
{
#Value = Model.DesignParams[i].DefaultValue,
#class = "form-control text-right",
#type = "text",
id = "_" + Model.DesignParams[i].ParamId,
uomid = Model.DesignParams[i].UOMId,
measureid = Model.DesignParams[i].MeasureId
}
})
The above code works fine using FireFox and Chrome and generates an input field that looks like this:
<input type="text" uomid="MBH" name="HeatOfRejection" measureid="HeatLoad"
id="_HeatOfRejection" class="form-control text-right text-box single-line"
value="5000.0">
But the same Razor code, identical #Model values viewed with IE generates this:
<input Value="5000" class="form-control text-right text-box single-line"
id="_HeatOfRejection" measureid="HeatLoad" name="HeatOfRejection"
type="text" uomid="MBH" value="" />
As you can see, there is a difference between the value= attribute generated for IE in that the value attribute that gets my actual value begins with an uppercase 'V' and the lowercase value is an empty string. I'm stumped on this...
Can anyone tell me why this is happening and possibly how to handle it?
This difference effects jQuery's ability to return the input's value with:
var value = $(inputfield).attr("value");
Maybe .val() will retrieve the input field value, but this is going to require a rewrite of core jQuery code that supports this page and others, so I wanted to ask if anyone can tell me why this 'Value=' gets created for IE only and if there is a way of overcoming the problem.
Update:
Changing #Value to #value (or just value) results in an empty value attribute in Firefox and IE:
<input type="text" value="" uomid="MBH" name="HeatOfRejection" measureid="HeatLoad"
id="_HeatOfRejection" class="form-control text-right text-box single-line">
As StuartLC points out, you are trying to get Html.Editor to do something it wasn't designed to do.
What happens when you pass a #value or #Value key to the htmlAttributes is that the rendering engine produces an attribute with that name in addition to the value attribute it's already generating:
<input type="text" name="n" value="something" value="somethingElse" />
or
<input type="text" name="n" value="something" Value="somethingElse" />
In both cases, you're giving the browser something bogus, so it can't be expected to exhibit predictable behavior.
As alluded above, Html.Editor has functionality to generate the value attribute based on the expression argument you pass to it. The problem is that you are using that incorrectly as well. The first argument to Html.Editor() needs to be an expression indicating the model property that the editor should be bound to. (e.g. the string value "DesignParams[0].ParamId") Nowadays, the preferred practice is to use the more modern EditorFor that takes a lambda function, as StuartLC showed in his post:
#Html.EditorFor(model => model.DesignParams[i].ParamId, ...)
You are "capitalising" the value html attribute. Change this to lower case...
#Value = Model.DesignParams[i].DefaultValue
as below ...
#value = Model.DesignParams[i].DefaultValue
IE is not the smartest of web browsers and there's definitely something wrong in the way Trident (they're parsing engine) validates elements' attributes as seen in these threads...
https://github.com/highslide-software/highcharts.com/issues/1978
Highcharts adds duplicate xmlns attribute to SVG element in IE
Also, as already noted somewhere else. What's the need for the Editor extension method? Isn't it simpler to just use TextBoxFor instead?
#Html.TextBoxFor(model => model.DesignParams[i].ParamId
, new
{
#class = "form-control text-right"
, uomid = Model.DesignParams[i].UOMId
, measureid = Model.DesignParams[i].MeasureId
})
Editor works with metadata. then you need to more about this,
http://aspadvice.com/blogs/kiran/archive/2009/11/29/Adding-html-attributes-support-for-Templates-2D00-ASP.Net-MVC-2.0-Beta_2D00_1.aspx
But the easiest way is go with
#model Namespace.ABCModel
#using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(model => model.DesignParams[i].ParamId, new { #class = "form-control text-right", uomid = Model.DesignParams[i].UOMId, measureid = Model.DesignParams[i].MeasureId })
}
You shouldn't be using invalid Html attributes in this way. Use the data- attributes in Html 5.
Also, your use of #Html.Editor(Model.DesignParams[i].ParamId (assuming ParamId is a string) deviates from the helper's purpose, which is to reflect the property with the given name off the Model, and use the value of this property as the Html value attribute on the input. (MVC will be looking for a property on the root model with whatever the value of ParamId is, which seems to silently fail FWR)
I would do the defaulting of Model.DesignParams[i].ParamId = Model.DesignParams[i].DefaultValue in the Controller beforehand, or in the DesignParams constructor.
#Html.EditorFor(m => m.DesignParams[0].ParamID,
new {
htmlAttributes = new
{
// Don't set value at all here - the value IS m.DesignParams[0].ParamID
#class = "form-control text-right",
#type = "text",
id = "_" + Model.DesignParams[i].ParamId,
data_uomid = Model.DesignParams[i].UOMId,
data_measureid = Model.DesignParams[i].MeasureId
}
Note that this will give the input name as DesignParams[0].ParamID, which would be needed to post the field back, if necessary.
Here's a Gist of some example code
(The underscore will be converted to a dash)
Use data() in jQuery to obtain these values:
var value = $(inputfield).data("uomid");

Tri-state Check box in HTML?

There is no way to have a tri-state check button (yes, no, null) in HTML, right?
Are there any simple tricks or work-arounds without having to render the whole thing by oneself?
Edit — Thanks to Janus Troelsen's comment, I found a better solution:
HTML5 defines a property for checkboxes called indeterminate
See w3c reference guide. To make checkbox appear visually indeterminate set it to true:
element.indeterminate = true;
Here is Janus Troelsen's fiddle. Note, however, that:
The indeterminate state cannot be set in the HTML markup, it can only be done via Javascript (see this JSfiddle test and this detailed article in CSS tricks)
This state doesn't change the value of the checkbox, it is only a visual cue that masks the input's real state.
Browser test: Worked for me in Chrome 22, Firefox 15, Opera 12 and back to IE7. Regarding mobile browsers, Android 2.0 browser and Safari mobile on iOS 3.1 don't have support for it.
Previous answer
Another alternative would be to play with the checkbox transparency
for the "some selected" state (as Gmail does used to
do in previous versions). It will require some javascript and a CSS
class. Here I put a particular example that handles a list with
checkable items and a checkbox that allows to select all/none of them.
This checkbox shows a "some selected" state when some of the list
items are selected.
Given a checkbox with an ID #select_all and several checkboxes with
a class .select_one,
The CSS class that fades the "select all" checkbox would be the
following:
.some_selected {
opacity: 0.5;
filter: alpha(opacity=50);
}
And the JS code that handles the tri-state of the select all checkbox
is the following:
$('#select_all').change (function ()
{
//Check/uncheck all the list's checkboxes
$('.select_one').attr('checked', $(this).is(':checked'));
//Remove the faded state
$(this).removeClass('some_selected');
});
$('.select_one').change (function ()
{
if ($('.select_one:checked').length == 0)
$('#select_all').removeClass('some_selected').attr('checked', false);
else if ($('.select_one:not(:checked)').length == 0)
$('#select_all').removeClass('some_selected').attr('checked', true);
else
$('#select_all').addClass('some_selected').attr('checked', true);
});
You can try it here: http://jsfiddle.net/98BMK/
You could use HTML's indeterminate IDL attribute on input elements.
My proposal would be using
three appropriate unicode characters for the three states e.g. ❓,✅,❌
a plain text input field (size=1)
no border
read only
display no cursor
onclick handler to toggle thru the three states
See examples at:
http://jsfiddle.net/wf_bitplan_com/941std72/8/
/**
* loops thru the given 3 values for the given control
*/
function tristate(control, value1, value2, value3) {
switch (control.value.charAt(0)) {
case value1:
control.value = value2;
break;
case value2:
control.value = value3;
break;
case value3:
control.value = value1;
break;
default:
// display the current value if it's unexpected
alert(control.value);
}
}
function tristate_Marks(control) {
tristate(control,'\u2753', '\u2705', '\u274C');
}
function tristate_Circles(control) {
tristate(control,'\u25EF', '\u25CE', '\u25C9');
}
function tristate_Ballot(control) {
tristate(control,'\u2610', '\u2611', '\u2612');
}
function tristate_Check(control) {
tristate(control,'\u25A1', '\u2754', '\u2714');
}
<input type='text'
style='border: none;'
onfocus='this.blur()'
readonly='true'
size='1'
value='❓' onclick='tristate_Marks(this)' />
<input style="border: none;"
id="tristate"
type="text"
readonly="true"
size="1"
value="❓"
onclick="switch(this.form.tristate.value.charAt(0)) {
case '&#x2753': this.form.tristate.value='✅'; break;
case '&#x2705': this.form.tristate.value='❌'; break;
case '&#x274C': this.form.tristate.value='❓'; break;
};" />
You can use radio groups to achieve that functionality:
<input type="radio" name="choice" value="yes" />Yes
<input type="radio" name="choice" value="No" />No
<input type="radio" name="choice" value="null" />null
Here is a runnable example using the mentioned indeterminate attribute:
const indeterminates = document.getElementsByClassName('indeterminate');
indeterminates['0'].indeterminate = true;
<form>
<div>
<input type="checkbox" checked="checked" />True
</div>
<div>
<input type="checkbox" />False
</div>
<div>
<input type="checkbox" class="indeterminate" />Indeterminate
</div>
</form>
Just run the code snippet to see how it looks like.
You can use an indeterminate state: http://css-tricks.com/indeterminate-checkboxes/. It's supported by the browsers out of the box and don't require any external js libraries.
I think that the most semantic way is using readonly attribute that checkbox inputs can have. No css, no images, etc; a built-in HTML property!
See Fiddle:
http://jsfiddle.net/chriscoyier/mGg85/2/
As described here in last trick:
http://css-tricks.com/indeterminate-checkboxes/
Like #Franz answer you can also do it with a select. For example:
<select>
<option></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
With this you can also give a concrete value that will be send with the form, I think that with javascript indeterminate version of checkbox, it will send the underline value of the checkbox.
At least, you can use it as a callback when javascript is disabled. For example, give it an id and in the load event change it to the javascript version of the checkbox with indeterminate status.
Besides all cited above, there are jQuery plugins that may help too:
for individual checkboxes:
jQuery-Tristate-Checkbox-plugin: http://vanderlee.github.io/tristate/
for tree-like behavior checkboxes:
jQuery Tristate: http://jlbruno.github.io/jQuery-Tristate-Checkbox-plugin/
EDIT
Both libraries uses the 'indeterminate' checkbox attribute, since this attribute in Html5 is just for styling (https://www.w3.org/TR/2011/WD-html5-20110113/number-state.html#checkbox-state), the null value is never sent to the server (checkboxes can only have two values).
To be able to submit this value to the server, I've create hidden counterpart fields which are populated on form submission using some javascript. On the server side, you'd need to check those counterpart fields instead of original checkboxes, of course.
I've used the first library (standalone checkboxes) where it's important to:
Initialize the checked, unchecked, indeterminate values
use .val() function to get the actual value
Cannot make work .state (probably my mistake)
Hope that helps.
Refering to #BoltClock answer, here is my solution for a more complex recursive method:
http://jsfiddle.net/gx7so2tq/2/
It might not be the most pretty solution but it works fine for me and is quite flexible.
I use two data objects defining the container:
data-select-all="chapter1"
and the elements itself:
data-select-some="chapter1"
Both having the same value. The combination of both data-objects within one checkbox allows sublevels, which are scanned recursively. Therefore two "helper" functions are needed to prevent the change-trigger.
Here other Example with simple jQuery and property data-checked:
$("#checkbox")
.click(function(e) {
var el = $(this);
switch (el.data('checked')) {
// unchecked, going indeterminate
case 0:
el.data('checked', 1);
el.prop('indeterminate', true);
break;
// indeterminate, going checked
case 1:
el.data('checked', 2);
el.prop('indeterminate', false);
el.prop('checked', true);
break;
// checked, going unchecked
default:
el.data('checked', 0);
el.prop('indeterminate', false);
el.prop('checked', false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="checkbox" name="checkbox" value="" checked id="checkbox"> Tri-State Checkbox </label>
As I needed something like this -without any plug-in- for script-generated checkboxes in a table... I ended up with this solution:
<!DOCTYPE html>
<html>
<body>
Toto <input type="checkbox" id="myCheck1" onclick="updateChkBx(this)" /><br />
Tutu <input type="checkbox" id="myCheck2" onclick="updateChkBx(this)" /><br />
Tata <input type="checkbox" id="myCheck3" onclick="updateChkBx(this)" /><br />
Tete <input type="checkbox" id="myCheck4" onclick="updateChkBx(this)" /><br />
<script>
var chkBoxState = [];
function updateChkBx(src) {
var idx = Number(src.id.substring(7)); // 7 to bypass the "myCheck" part in each checkbox id
if(typeof chkBoxState[idx] == "undefined") chkBoxState[idx] = false; // make sure we can use stored state at first call
// the problem comes from a click on a checkbox both toggles checked attribute and turns inderminate attribute to false
if(chkBoxState[idx]) {
src.indeterminate = false;
src.checked = false;
chkBoxState[idx] = false;
}
else if (!src.checked) { // passing from checked to unchecked
src.indeterminate = true;
src.checked = true; // force considering we are in a checked state
chkBoxState[idx] = true;
}
}
// to know box state, just test indeterminate, and if not indeterminate, test checked
</script>
</body>
</html>
A short snippet using an auxiliary variable and indeterminate:
cb1.state = 1
function toggle_tristate(cb) {
cb.state = ++cb.state % 3 // cycle through 0,1,2
if (cb.state == 0) {
cb.indeterminate = true;
cb.checked = true; // after 'indeterminate' the state 'false' follows
}
}
<input id="cb1" type="checkbox" onclick="toggle_tristate(this)">
Only state==0 is captured. The rest is handle automatically.
http://jsfiddle.net/6vyek2c5
You'll need to use javascript/css to fake it.
Try here for an example: http://www.dynamicdrive.com/forums/archive/index.php/t-26322.html
It's possible to have HTML form elements disabled -- wouldn't that do? Your users would see it in one of three states, i.e. checked, unchecked, and disabled, which would be greyed out and not clickable. To me, that seems similar to "null" or "not applicable" or whatever you're looking for in that third state.
There's a simple JavaScript tri-state input field implementation at
https://github.com/supernifty/tristate-checkbox
The jQuery plugin "jstree" with the checkbox plugin can do this.
http://www.jstree.com/documentation/checkbox
-Matt
Building on the answers above using the indeterminate state, I've come up with a little bit that handles individual checkboxes and makes them tri-state.
MVC razor uses 2 inputs per checkbox anyway (the checkbox and a hidden with the same name to always force a value in the submit). MVC uses things like "true" as the checkbox value and "false" as the hidden of the same name; makes it amenable to boolean use in API calls. This snippet uses a third hidden state to persist the last request values across submits.
Checkboxes initialized with the below will start indeterminate. Checking once turns on the checkbox. Checking twice turns off the checkbox (returning the hidden value of the same name). Checking a third time returns it to indeterminate (and clears out the hidden so a submit will produce a blank).
The page also populates another hidden (e.g., triBox2Orig) with whatever value was on the query string to start, so the 3 states can be initialized and persisted between submits.
$(document).ready(function () {
var initCheckbox = function (chkBox)
{
var hidden = $('[name="' + $(chkBox).prop("name") + '"][type="hidden"]');
var hiddenOrig = $('[name="' + $(chkBox).prop("name") + 'Orig"][type="hidden"]').prop("value");
hidden.prop("origValue", hidden.prop("value"));
if (!chkBox.prop("checked") && !hiddenOrig) chkBox.prop("indeterminate", true);
if (chkBox.prop("indeterminate")) hidden.prop("value", null);
chkBox.change(checkBoxToggleFun);
}
var checkBoxToggleFun = function ()
{
var isChecked = $(this).prop('checked');
var hidden = $('[name="' + $(this).prop("name") + '"][type="hidden"]');
var thirdState = isChecked && hidden.prop("value") === hidden.prop("origValue");
if (thirdState) { // on 3rd click of a checkbox, set it back to indeterminate
$(this).prop("indeterminate", true);
$(this).prop('checked', false);
}
hidden.prop("value", thirdState ? null : hidden.prop("origValue"));
};
var chkBox = $('#triBox1');
initCheckbox(chkBox);
chkBox = $('#triBox2');
initCheckbox(chkBox);
});

POST unchecked HTML checkboxes

I've got a load of checkboxes that are checked by default. My users will probably uncheck a few (if any) of the checkboxes and leave the rest checked.
Is there any way to make the form POST the checkboxes that are not checked, rather than the ones that are checked?
The solution I liked the most so far is to put a hidden input with the same name as the checkbox that might not be checked. I think it works so that if the checkbox isn't checked, the hidden input is still successful and sent to the server but if the checkbox is checked it will override the hidden input before it. This way you don't have to keep track of which values in the posted data were expected to come from checkboxes.
<form>
<input type='hidden' value='0' name='selfdestruct'>
<input type='checkbox' value='1' name='selfdestruct'>
</form>
Add a hidden input for the checkbox with a different ID:
<input id='testName' type='checkbox' value='Yes' name='testName'>
<input id='testNameHidden' type='hidden' value='No' name='testName'>
Before submitting the form, disable the hidden input based on the checked condition:
form.addEventListener('submit', () => {
if(document.getElementById("testName").checked) {
document.getElementById('testNameHidden').disabled = true;
}
}
I solved it by using vanilla JavaScript:
<input type="hidden" name="checkboxName" value="0"><input type="checkbox" onclick="this.previousSibling.value=1-this.previousSibling.value">
Be careful not to have any spaces or linebreaks between this two input elements!
You can use this.previousSibling.previousSibling to get "upper" elements.
With PHP you can check the named hidden field for 0 (not set) or 1 (set).
My personal favorite is to add a hidden field with the same name that will be used if the check-box is unchecked. But the solution is not as easy as it may seems.
If you add this code:
<form>
<input type='hidden' value='0' name='selfdestruct'>
<input type='checkbox' value='1' name='selfdestruct'>
</form>
The browser will not really care about what you do here. The browser will send both parameters to the server, and the server has to decide what to do with them.
PHP for example takes the last value as the one to use (see: Authoritative position of duplicate HTTP GET query keys)
But other systems I worked with (based on Java) do it the way around - they offer you only the first value.
.NET instead will give you an array with both elements instead
I'll try to test this with node.js, Python and Perl at sometime.
you don't need to create a hidden field for all checkboxes just copy my code.
it will change the value of checkbox if not checked the value will assign 0 and if checkbox checked then assign value into 1
$("form").submit(function () {
var this_master = $(this);
this_master.find('input[type="checkbox"]').each( function () {
var checkbox_this = $(this);
if( checkbox_this.is(":checked") == true ) {
checkbox_this.attr('value','1');
} else {
checkbox_this.prop('checked',true);
//DONT' ITS JUST CHECK THE CHECKBOX TO SUBMIT FORM DATA
checkbox_this.attr('value','0');
}
})
})
A common technique around this is to carry a hidden variable along with each checkbox.
<input type="checkbox" name="mycheckbox" />
<input type="hidden" name="mycheckbox.hidden"/>
On the server side, we first detect list of hidden variables and for each of the hidden variable, we try to see if the corresponding checkbox entry is submitted in the form data or not.
The server side algorithm would probably look like:
for input in form data such that input.name endswith .hidden
checkboxName = input.name.rstrip('.hidden')
if chceckbName is not in form, user has unchecked this checkbox
The above doesn't exactly answer the question, but provides an alternate means of achieving similar functionality.
I know this question is 3 years old but I found a solution that I think works pretty well.
You can do a check if the $_POST variable is assigned and save it in a variable.
$value = isset($_POST['checkboxname'] ? 'YES' : 'NO';
the isset() function checks if the $_POST variable is assigned. By logic if it is not assigned then the checkbox is not checked.
$('input[type=checkbox]').on("change",function(){
var target = $(this).parent().find('input[type=hidden]').val();
if(target == 0)
{
target = 1;
}
else
{
target = 0;
}
$(this).parent().find('input[type=hidden]').val(target);
});
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
If you leave out the name of the checkbox it doesn't get passed.
Only the test_checkbox array.
You can do some Javascript in the form's submit event. That's all you can do though, there's no way to get browsers to do this by themselves. It also means your form will break for users without Javascript.
Better is to know on the server which checkboxes there are, so you can deduce that those absent from the posted form values ($_POST in PHP) are unchecked.
I also like the solution that you just post an extra input field, using JavaScript seems a little hacky to me.
Depending on what you use for you backend will depend on which input goes first.
For a server backend where the first occurrence is used (JSP) you should do the following.
<input type="checkbox" value="1" name="checkbox_1"/>
<input type="hidden" value="0" name="checkbox_1"/>
For a server backend where the last occurrence is used (PHP,Rails) you should do the following.
<input type="hidden" value="0" name="checkbox_1"/>
<input type="checkbox" value="1" name="checkbox_1"/>
For a server backend where all occurrences are stored in a list data type ([],array). (Python / Zope)
You can post in which ever order you like, you just need to try to get the value from the input with the checkbox type attribute. So the first index of the list if the checkbox was before the hidden element and the last index if the checkbox was after the hidden element.
For a server backend where all occurrences are concatenated with a comma (ASP.NET / IIS)
You will need to (split/explode) the string by using a comma as a delimiter to create a list data type. ([])
Now you can attempt to grab the first index of the list if the checkbox was before the hidden element and grab the last index if the checkbox was after the hidden element.
image source
I would actually do the following.
Have my hidden input field with the same name with the checkbox input
<input type="hidden" name="checkbox_name[]" value="0" />
<input type="checkbox" name="checkbox_name[]" value="1" />
and then when i post I first of all remove the duplicate values picked up in the $_POST array, atfer that display each of the unique values.
$posted = array_unique($_POST['checkbox_name']);
foreach($posted as $value){
print $value;
}
I got this from a post remove duplicate values from array
"I've gone with the server approach. Seems to work fine - thanks. – reach4thelasers Dec 1 '09 at 15:19" I would like to recommend it from the owner. As quoted: javascript solution depends on how the server handler (I didn't check it)
such as
if(!isset($_POST["checkbox"]) or empty($_POST["checkbox"])) $_POST["checkbox"]="something";
Most of the answers here require the use of JavaScript or duplicate input controls. Sometimes this needs to be handled entirely on the server-side.
I believe the (intended) key to solving this common problem is the form's submission input control.
To interpret and handle unchecked values for checkboxes successfully you need to have knowledge of the following:
The names of the checkboxes
The name of the form's submission input element
By checking whether the form was submitted (a value is assigned to the submission input element), any unchecked checkbox values can be assumed.
For example:
<form name="form" method="post">
<input name="value1" type="checkbox" value="1">Checkbox One<br/>
<input name="value2" type="checkbox" value="1" checked="checked">Checkbox Two<br/>
<input name="value3" type="checkbox" value="1">Checkbox Three<br/>
<input name="submit" type="submit" value="Submit">
</form>
When using PHP, it's fairly trivial to detect which checkboxes were ticked.
<?php
$checkboxNames = array('value1', 'value2', 'value3');
// Persisted (previous) checkbox state may be loaded
// from storage, such as the user's session or a database.
$checkboxesThatAreChecked = array();
// Only process if the form was actually submitted.
// This provides an opportunity to update the user's
// session data, or to persist the new state of the data.
if (!empty($_POST['submit'])) {
foreach ($checkboxNames as $checkboxName) {
if (!empty($_POST[$checkboxName])) {
$checkboxesThatAreChecked[] = $checkboxName;
}
}
// The new state of the checkboxes can be persisted
// in session or database by inspecting the values
// in $checkboxesThatAreChecked.
print_r($checkboxesThatAreChecked);
}
?>
Initial data could be loaded on each page load, but should be only modified if the form was submitted. Since the names of the checkboxes are known beforehand, they can be traversed and inspected individually, so that the the absence of their individual values indicates that they are not checked.
I've tried Sam's version first.
Good idea, but it causes there to be multiple elements in the form with the same name. If you use any javascript that finds elements based on name, it will now return an array of elements.
I've worked out Shailesh's idea in PHP, it works for me.
Here's my code:
/* Delete '.hidden' fields if the original is present, use '.hidden' value if not. */
foreach ($_POST['frmmain'] as $field_name => $value)
{
// Only look at elements ending with '.hidden'
if ( !substr($field_name, -strlen('.hidden')) ) {
break;
}
// get the name without '.hidden'
$real_name = substr($key, strlen($field_name) - strlen('.hidden'));
// Create a 'fake' original field with the value in '.hidden' if an original does not exist
if ( !array_key_exists( $real_name, $POST_copy ) ) {
$_POST[$real_name] = $value;
}
// Delete the '.hidden' element
unset($_POST[$field_name]);
}
You can also intercept the form.submit event and reverse check before submit
$('form').submit(function(event){
$('input[type=checkbox]').prop('checked', function(index, value){
return !value;
});
});
I use this block of jQuery, which will add a hidden input at submit-time to every unchecked checkbox. It will guarantee you always get a value submitted for every checkbox, every time, without cluttering up your markup and risking forgetting to do it on a checkbox you add later. It's also agnostic to whatever backend stack (PHP, Ruby, etc.) you're using.
// Add an event listener on #form's submit action...
$("#form").submit(
function() {
// For each unchecked checkbox on the form...
$(this).find($("input:checkbox:not(:checked)")).each(
// Create a hidden field with the same name as the checkbox and a value of 0
// You could just as easily use "off", "false", or whatever you want to get
// when the checkbox is empty.
function(index) {
var input = $('<input />');
input.attr('type', 'hidden');
input.attr('name', $(this).attr("name")); // Same name as the checkbox
input.attr('value', "0"); // or 'off', 'false', 'no', whatever
// append it to the form the checkbox is in just as it's being submitted
var form = $(this)[0].form;
$(form).append(input);
} // end function inside each()
); // end each() argument list
return true; // Don't abort the form submit
} // end function inside submit()
); // end submit() argument list
$('form').submit(function () {
$(this).find('input[type="checkbox"]').each( function () {
var checkbox = $(this);
if( checkbox.is(':checked')) {
checkbox.attr('value','1');
} else {
checkbox.after().append(checkbox.clone().attr({type:'hidden', value:0}));
checkbox.prop('disabled', true);
}
})
});
I see this question is old and has so many answers, but I'll give my penny anyway.
My vote is for the javascript solution on the form's 'submit' event, as some has pointed out. No doubling the inputs (especially if you have long names and attributes with php code mixed with html), no server side bother (that would require to know all field names and to check them down one by one), just fetch all the unchecked items, assign them a 0 value (or whatever you need to indicate a 'not checked' status) and then change their attribute 'checked' to true
$('form').submit(function(e){
var b = $("input:checkbox:not(:checked)");
$(b).each(function () {
$(this).val(0); //Set whatever value you need for 'not checked'
$(this).attr("checked", true);
});
return true;
});
this way you will have a $_POST array like this:
Array
(
[field1] => 1
[field2] => 0
)
What I did was a bit different. First I changed the values of all the unchecked checkboxes. To "0", then selected them all, so the value would be submitted.
function checkboxvalues(){
$("#checkbox-container input:checkbox").each(function({
if($(this).prop("checked")!=true){
$(this).val("0");
$(this).prop("checked", true);
}
});
}
I would prefer collate the $_POST
if (!$_POST['checkboxname']) !$_POST['checkboxname'] = 0;
it minds, if the POST doesn't have have the 'checkboxname'value, it was unckecked so, asign a value.
you can create an array of your ckeckbox values and create a function that check if values exist, if doesn`t, it minds that are unchecked and you can asign a value
Might look silly, but it works for me. The main drawback is that visually is a radio button, not a checkbox, but it work without any javascript.
HTML
Initialy checked
<span><!-- set the check attribute for the one that represents the initial value-->
<input type="radio" name="a" value="1" checked>
<input type="radio" name="a" value="0">
</span>
<br/>
Initialy unchecked
<span><!-- set the check attribute for the one that represents the initial value-->
<input type="radio" name="b" value="1">
<input type="radio" name="b" value="0" checked>
</span>
and CSS
span input
{position: absolute; opacity: 0.99}
span input:checked
{z-index: -10;}
span input[value="0"]
{opacity: 0;}
fiddle here
I'd like to hear any problems you find with this code, cause I use it in production
The easiest solution is a "dummy" checkbox plus hidden input if you are using jquery:
<input id="id" type="hidden" name="name" value="1/0">
<input onchange="$('#id').val(this.checked?1:0)" type="checkbox" id="dummy-id"
name="dummy-name" value="1/0" checked="checked/blank">
Set the value to the current 1/0 value to start with for BOTH inputs, and checked=checked if 1. The input field (active) will now always be posted as 1 or 0. Also the checkbox can be clicked more than once before submission and still work correctly.
Example on Ajax actions is(':checked') used jQuery instead of .val();
var params = {
books: $('input#users').is(':checked'),
news : $('input#news').is(':checked'),
magazine : $('input#magazine').is(':checked')
};
params will get value in TRUE OR FALSE..
Checkboxes usually represent binary data that are stored in database as Yes/No, Y/N or 1/0 values. HTML checkboxes do have bad nature to send value to server only if checkbox is checked! That means that server script on other site must know in advance what are all possible checkboxes on web page in order to be able to store positive (checked) or negative (unchecked) values. Actually only negative values are problem (when user unchecks previously (pre)checked value - how can server know this when nothing is sent if it does not know in advance that this name should be sent). If you have a server side script which dynamically creates UPDATE script there's a problem because you don't know what all checkboxes should be received in order to set Y value for checked and N value for unchecked (not received) ones.
Since I store values 'Y' and 'N' in my database and represent them via checked and unchecked checkboxes on page, I added hidden field for each value (checkbox) with 'Y' and 'N' values then use checkboxes just for visual representation, and use simple JavaScript function check() to set value of if according to selection.
<input type="hidden" id="N1" name="N1" value="Y" />
<input type="checkbox"<?php if($N1==='Y') echo ' checked="checked"'; ?> onclick="check(this);" />
<label for="N1">Checkbox #1</label>
use one JavaScript onclick listener and call function check() for each checkboxe on my web page:
function check(me)
{
if(me.checked)
{
me.previousSibling.previousSibling.value='Y';
}
else
{
me.previousSibling.previousSibling.value='N';
}
}
This way 'Y' or 'N' values are always sent to server side script, it knows what are fields that should be updated and there's no need for conversion of checbox "on" value into 'Y' or not received checkbox into 'N'.
NOTE: white space or new line is also a sibling so here I need .previousSibling.previousSibling.value. If there's no space between then only .previousSibling.value
You don't need to explicitly add onclick listener like before, you can use jQuery library to dynamically add click listener with function to change value to all checkboxes in your page:
$('input[type=checkbox]').click(function()
{
if(this.checked)
{
$(this).prev().val('Y');
}
else
{
$(this).prev().val('N');
}
});
#cpburnz got it right but to much code, here is the same idea using less code:
JS:
// jQuery OnLoad
$(function(){
// Listen to input type checkbox on change event
$("input[type=checkbox]").change(function(){
$(this).parent().find('input[type=hidden]').val((this.checked)?1:0);
});
});
HTML (note the field name using an array name):
<div>
<input type="checkbox" checked="checked">
<input type="hidden" name="field_name[34]" value="1"/>
</div>
<div>
<input type="checkbox">
<input type="hidden" name="field_name[35]" value="0"/>
</div>
<div>
And for PHP:
<div>
<input type="checkbox"<?=($boolean)?' checked="checked"':''?>>
<input type="hidden" name="field_name[<?=$item_id?>]" value="<?=($boolean)?1:0?>"/>
</div>
All answers are great, but if you have multiple checkboxes in a form with the same name and you want to post the status of each checkbox. Then i have solved this problem by placing a hidden field with the checkbox (name related to what i want).
<input type="hidden" class="checkbox_handler" name="is_admin[]" value="0" />
<input type="checkbox" name="is_admin_ck[]" value="1" />
then control the change status of checkbox by below jquery code:
$(documen).on("change", "input[type='checkbox']", function() {
var checkbox_val = ( this.checked ) ? 1 : 0;
$(this).siblings('input.checkbox_handler').val(checkbox_val);
});
now on change of any checkbox, it will change the value of related hidden field. And on server you can look only to hidden fields instead of checkboxes.
Hope this will help someone have this type of problem. cheer :)
You can add hidden elements before submitting form.
$('form').submit(function() {
$(this).find('input[type=checkbox]').each(function (i, el) {
if(!el.checked) {
var hidden_el = $(el).clone();
hidden_el[0].checked = true;
hidden_el[0].value = '0';
hidden_el[0].type = 'hidden'
hidden_el.insertAfter($(el));
}
})
});
The problem with checkboxes is that if they are not checked then they are not posted with your form. If you check a checkbox and post a form you will get the value of the checkbox in the $_POST variable which you can use to process a form, if it's unchecked no value will be added to the $_POST variable.
In PHP you would normally get around this problem by doing an isset() check on your checkbox element. If the element you are expecting isn't set in the $_POST variable then we know that the checkbox is not checked and the value can be false.
if(!isset($_POST['checkbox1']))
{
$checkboxValue = false;
} else {
$checkboxValue = $_POST['checkbox1'];
}
But if you have created a dynamic form then you won't always know the name attribute of your checkboxes, if you don't know the name of the checkbox then you can't use the isset function to check if this has been sent with the $_POST variable.
function SubmitCheckBox(obj) {
obj.value = obj.checked ? "on" : "off";
obj.checked = true;
return obj.form.submit();
}
<input type=checkbox name="foo" onChange="return SubmitCheckBox(this);">
If you want to submit an array of checkbox values (including un-checked items) then you could try something like this:
<form>
<input type="hidden" value="0" name="your_checkbox_array[]"><input type="checkbox">Dog
<input type="hidden" value="0" name="your_checkbox_array[]"><input type="checkbox">Cat
</form>
$('form').submit(function(){
$('input[type="checkbox"]:checked').prev().val(1);
});