i have a list with checkboxes in the table , when i click select all function , it selects all checkbox including disabled ones, i neeed to exclude the disabled checkbox .
<li><a #click.prevent="selectAll" id="cardSelectAllAId">
SelectAll</a></li>
<single-checkbox class="checkbox "
inputId="card.data.id"
v-if="card.data.id"
#change="change(card.data)"
:value="card.data.selected"
:disabled="!card.data.licenseEnabled">
selectAll() {
for (let i = 0; i < this.cards.length; i += 1) {
if (this.cards[i].selected !== undefined) {
this.cards[i].selected = true;
}
},
You can try something like this in your function-
// Reset all selected first
this.cards.map((x) => x.selected = false);
// Filter and then set selected to true
this.cards
.filter((x) => x.data.licenseEnabled)
.map((x) => x.selected = true);
if(this.cards[i].selected !== undefined && this.cards[i].licenseEnabled)
this works
I have a group of 3 checkboxes and I need to apply some conditions/restrictions for them.
For example, if I tick the first checkbox {{UTEP}} i'll have to disable the last one ValĂȘncias.
I have the following code:
var _restricoes = [[1, 2]];
$($('#conteudoCategorias').find('.clsF3MInput')).on('click', function (e) {
debugger
//get elems
var _id = parseInt($(this).attr("id").replace("CheckBox", ""));
for (var i = 0; i < _restricoes.length; i++) {
//get item
var _item = _restricoes[i];
//verifica se existe
var _existe = $.grep(_item, (x) => x === _id)[0];
if (_existe && CategoriasAnexosVerificaCheck($(this)) === true) {
//get other value
var _otherValue = $.grep(_item, (x) => x !== _id)[0];
//bloquear elementos
var elemsBloquear = $.grep($('#conteudoCategorias :input'), function (elem) {
return elem.getAttribute('id') !== 'CheckBox' + _id &&
elem.getAttribute('id') !== 'CheckBox' + _otherValue;
});
$(elemsBloquear).attr('disabled', true);
//desbloquear elementos
var elemsDesbBloquear = $.grep($('#conteudoCategorias :input'), function (elem) {
elem.getAttribute('id') === 'CheckBox' + _id;
elem.getAttribute('id') === 'CheckBox' + _otherValue;
});
$(elemsDesbBloquear).attr('disabled', false);
}
}
});
When I uncheck the {{UTEP}} I need to enable the checkbox ValĂȘncias again, but I can't get to it.
the array _restricoes contains the ids of the checkboxes that can be checked. If I check the first one, I can check the second one, and vice-versa. The array will have more conditions/restrictions, like this for example: _restricoes = [[1, 2], [1, 4]];
Note: The Ids of the checkboxes are dynamic, they are generated from the server, puting it simpler: the number of registrations are the checkboxes.
Your code is a weird combination between jQuery and javascript. Here is a jQuery solution how you can change the enabled property based on the checked property of another checkbox.
$('#utepId').on('change', function(){
//when #utepId is checked disable #ValenciasId
$('#ValenciasId').prop('disabled', $(this).prop('checked'));
//when #utepId is checked uncheck #ValenciasId
if($(this).prop('checked')) {
$('#ValenciasId').prop('checked', false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="utepId" type=checkbox /><label for="utepId">utep</label>
<input id="candbId" type=checkbox /><label for="candbId">candb</label>
<input id="ValenciasId" type=checkbox /><label for="ValenciasId">ValĂȘncias</label>
I can't wrap my head around this. I have this checkbox:
<input id="copy" name="varcopy" onkeyup="saveValue(this)" tabindex="4"
form="contact_form_id" type="checkbox" value="sendacopy" checked="checked" />
I need to store if the checkbox is checked or unchecked on page reload (whether the checkbox is actived/deactivated by spacebar or on mouseclick). I want to use localStorage for this, in plain JavaScript, no jQuery.
I have these functions to save and restore values of input fields (it works for all text inputs, but not for the checkbox):
function saveValue(e) {
var id = e.id;
var val = e.value;
localStorage.setItem(id, val);
}
function getSavedValue(v) {
if (localStorage.getItem(v) === null) {
return "";
}
return localStorage.getItem(v);
}
I did much research on the net, but I can't find what I specifically need. Please be gentle on me, I'm a beginner. This is what I tried to do with these 2 functions, but it doesn't work at all:
function saveValue(e) {
var id = e.id;
var val = e.value;
if (id == "copy") {
val = e.checked;
}
localStorage.setItem(id, val);
}
function getSavedValue(v) {
if (localStorage.getItem(v) === null) {
return "";
}
if (v == "copy") {
if (localStorage.getItem(v) == true)
return "true";
if (localStorage.getItem(v) == false)
return "false";
}
return localStorage.getItem(v);
}
This is how I invoke the getSavedValue() function:
document.getElementById("copy").value = getSavedValue("copy");
Ok, I'm making progress, this is my checkbox:
<input id="copy" name="varcopy" onkeyup="saveChecked(this)"
onmouseup="saveChecked(this)" tabindex="4"
form="contact_form_id" type="checkbox" />
These are my functions:
function saveChecked(e) {
var id = e.id;
var val = e.checked?1:0;
localStorage.setItem(id, val);
}
function getSavedValue(v) {
if (localStorage.getItem(v) === null) {
return "";
}
return localStorage.getItem(v);
}
And this is the invocation:
document.getElementById("copy").checked = !!getSavedValue("copy");
The problem is it always defaults to true, or always defaults to false. It doesn't switch.
This can be achieved as simple as follows:
var isChecked = !!getSavedValue('someKey');
var checkbox = document.getElementById('copy');
checkbox.checked = isChecked;
!!getSavedValue('someKey'); converts the value returned by your function into a boolean. An empty string, undefined and null will be converted to false and anything else will be converted to true.
Here is modified saveValue function, you can use it.
function saveValue(e) {
var id = e.id;
var val = e.value;
if(e.type === 'checkbox') {
val = e.checked?1:0;
}
localStorage.setItem(id, val);
}
It seems the checked attribute on a checkbox returns either true or false. (Somehow also it is true when unchecked, and false when checked) Problem is that if I do this:
val = e.checked?1:0;
it will always return 1. I think the checked attribute returns a string, not a boolean, so when I do the above in JavaScript, it will always be a non-empty string, meaning it will return true. I had to do this instead:
var val = "";
if (e.checked != true) { //Not-equals because true is unchecked, false is checked
val = "1";
}
Now it works, the checkbox remembers its state on page reload.
The following example will do that for you...
Enjoy... :-)
<script>
function saveData(e) {
let id = e.id;
let val;
if (e.type === 'checkbox'){
val = e.checked;
}else{
val = e.value;
}
localStorage.setItem(id, val);
}
function loadFieldData(id){
let elm = document.getElementById(id);
let value = localStorage.getItem(id);
if (elm) {
if (elm.type === 'checkbox') {
elm.checked = Boolean(value);
}else{
elm.value = value;
}
}
}
function loadData() {
loadFieldData('text1');
loadFieldData('copy');
}
</script>
<body>
<input id="text1" onkeyup="saveData(this)" onchange="saveData(this)" type="text" />
<br/>
<input id="copy" onchange="saveData(this)" type="checkbox" />
<br/>
<br/>
<input type="button" onclick="loadData()" value="Load Data" />
</body>
How can I modify this example so it can get values from checkboxes that aren't checked?
I want all checkboxes to have a value, if it hasn't been checked I want to get its value as false.
<input type="checkbox" name="Check01" value="true" />
<input type="checkbox" name="Check02" value="true" checked="checked" />
Default behavior
$("form").serializeArray();
// [Check02 = true]
Expected behavior
$("form").serializeArray();
// [Check01 = false, Check02 = true]
It's probably easiest to just do it yourself:
var serialized = $('input:checkbox').map(function() {
return { name: this.name, value: this.checked ? this.value : "false" };
});
If there are other inputs, then you could serialize the form, and then find the unchecked checkboxes with something like the above and append that result to the first array.
serializeArray ignores the checkboxes which are not checked. You can try something like this.
Working demo
var serializedObj = {};
$("form input:checkbox").each(function(){
serializedObj[this.name] = this.checked;
});
you can use this get unchecked values
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
var $radio = $('input[type=radio],input[type=checkbox]',this);
$.each($radio,function(){
if(!o.hasOwnProperty(this.name)){
o[this.name] = '';
}
});
return o;
};
code samples
another option is to just look at the source code for serializeArray and remove (or modify) the call to filter. I Just took that function and created a new one called serializeArrayAll like this:
$.fn.serializeArrayAll = function() {
var rCRLF = /\r?\n/g;
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
/* this is what is excluding the unchecked checkboxes (and also other disabled options)
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
*/
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
};
Here's how I implemented a simple override of $.serializeArray which fixes the default serialization behaviour for checkboxes, and default behaviour is retained for all other types.
In the code below, missed checkboxes are injected into the original serialized array. Checkbox state is returned as "true" (instead of "on") or "false" depending on if it is checked or not.
(function ($) {
var _base_serializeArray = $.fn.serializeArray;
$.fn.serializeArray = function () {
var a = _base_serializeArray.apply(this);
$.each(this.find("input"), function (i, e) {
if (e.type == "checkbox") {
e.checked
? a[i].value = "true"
: a.splice(i, 0, { name: e.name, value: "false" })
}
});
return a;
};
})(jQuery);
You could customize this to return "on"/"off" or true/false.
Update: Fixed code based on bug found by #shyammakwana.me.
you can add a hidden false value for every checkbox:
<input type="checkbox" name="Check01" value="true" /><input name="Check01" type="hidden" value="false" />
<input type="checkbox" name="Check02" value="true" checked="checked" /><input name="Check02" type="hidden" value="false" />
You will only get "false" values for unchecked checkboxes and both "true" and "false" for checked checkboxes, so you can remove the duplicates like this:
var params = {};
$.each($('form').serializeArray(), function (index, value) {
params[value.name] = params[value.name] ? params[value.name] || value.value : value.value;
});
console.log(params); // outputs: {"Check01":"false","Check02":"true"}
I made my own new solution based on the answers by #Pointy, #Ben, and the original jQuery code. The answer from #Pointy had odd behavior that returned contexts for checkboxes, this fixes that problem. The answer from #Ben was also not acting properly because it always returned checkbox = on even if it was unchecked.
$.fn.serializeArrayWithCheckboxes = function() {
var rCRLF = /\r?\n/g;
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.map(function( i, elem ){
var val = jQuery( this ).val();
if (val == null) {
return val == null
//next 2 lines of code look if it is a checkbox and set the value to blank
//if it is unchecked
} else if (this.type == "checkbox" && this.checked == false) {
return { name: this.name, value: this.checked ? this.value : ""}
//next lines are kept from default jQuery implementation and
//default to all checkboxes = on
} else {
return jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}
}).get();
};
Using the jQuery plugin serializeJSON, you can use the data-unchecked-value attribute to specify the value when unchecked:
<input type="checkbox" name="Check01" value="true" data-unchecked-value="false" />
<input type="checkbox" name="Check02" value="true" data-unchecked-value="false" checked="checked" />
JavaScript:
$('input').serializeJSON({ parseBooleans: true });
// returns => { 'Check01' : false, 'Check02' : true }
#SNag's answer worker almost 99% just with little bit correction.
Change below line
from :
$.each(this, function (i, e) {
to:
$.each(this.find('input'), function (i, e) {
Explanation: As this was not working because this returned form element. So on form .each won't give us all input elements inside form. So I did this correction and it worked like charm.
Yet Another SerializeArray()
This implementation is again based on jQuery's original code, but I needed it for some Bootstrap's "switch" checkboxes with two different values.
$.fn.serializeArrayWC = function() {
var rCRLF = /\r?\n/g;
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.map(function(i, elem){
if (this.type == "checkbox") {
// Bootstrap checkboxes with two different values.
if (jQuery(this).hasClass("switched")) {
// Always return value (either on-value or off-value).
return { name: this.name, value: this.value };
}
// Normal checkboxes. Unchecked checkboxed are not returned.
if (!this.checked) {
// This will be removed by the !!f filter, below.
return false;
}
// Return the value, or "on".
return { name: this.name, value: this.value||"on" };
}
var val = jQuery(this).val();
if (val == null) {
return { name: elem.name, value: null };
} else {
return jQuery.isArray(val) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}
})
.filter(function(i, f){ return !!f; })
.get();
};
You can append unchecked checkbox data to .serializeArray result:
var formData = $("#mybaseelement").serializeArray();
$('#mybaseelement input[type="checkbox"]:not(:checked)').each(function(i, e) {
formData.push({name: e.getAttribute("name"), value: false});
});
This is the least invasive solution I can come up with.
var fields = $("form").serializeArray();
$('form input[type=checkbox]').map(function() {
if( !this.checked )
{
fields.push({ name: this.name, value: "off" });
}
});
I have a main row and some other rows underneath that main row like this:
[checkbox] Main heading row
[checkbox] first child row
[checkbox] second child row
When I click on the child row, it should check the parent (main) row automatically. Problem is that it doesn't check it first time I click it. I have to check the first child row first, then uncheck the first child row and then check first child row again to get the parent (main) row get checked. I want the parent row get checked as soon as any of the child rows get checked.
I am using the following code
function checkbox_click(){
var n = event.srcElement;
if(n.parentElement.id == "row"){
n = n.parentElement;
}
if(n.id == "row"){
alert("ID: 1");
n.rs = n.parentElement;
if(this.multiSelect == 0){ // single select
alert("ID: 2");
n.all[0].checked = 1;
this.selectedRows = [ n ];
if(this.lastClicked && this.lastClicked != n){
this.lastClicked.all[0].checked = 0;
this.lastClicked.style.color = "000099";
this.lastClicked.style.backgroundColor = "";
}
} else {
alert("ID: 3");
n.all[0].click();
}
if(this.parentElement == pg.procs) {
alert("ID: 4");
var terminate = false;
var counter = 0;
if(n.className == "proc") {
alert("ID: 5");
z = n.nextSibling;
while(z.id == "row" && z.className != "proc" && !terminate) {
alert("ID: 6");
z.all[0].checked = 0;
z.style.backgroundColor = z.className == "w" ? "ffffff" : "ffffcc";
counter++;
if(counter > 1000) terminate = true;
z = z.nextSibling;
}
} else {
$(".row input").change(function() {
alert("ID: 7");
var $row= $(this).closest(".row");
var $main_row = $row.prev('.proc').length ? $row.prev('.proc') : $row.prevUntil(".proc").prev();
$main_row.find(":checkbox").attr("checked", function(i,attr) {
return $main_row.nextUntil('.proc').filter(':has(input:checked)').length ? "checked" : false;
});
});
$(".proc input").change(function() {
alert("ID: 8");
$(this).closest(".proc").nextUntil('.proc').children(':checkbox').attr('checked', this.checked);
});
}
If you want to check the parent checkbox when one of the child checkboxes is checked, I would suggest using a common class for the child checkboxes, and a unique id attribute for the parent checkbox (or store it as a variable).
Let's assume you have a structured HTML document that contains something like the following:
<div>
<input type="checkbox" name="ckparent" id="ckparent" />
<label for="ckparent">Parent</label>
<div>
<input type="checkbox" name="ckchild1" id="ckchild1" class="ckchild" />
<label for="ckchild1">Child 1</label>
</div>
<div>
<input type="checkbox" name="ckchild2" id="ckchild2" class="ckchild" />
<label for="ckchild2">Child 2</label>
</div>
</div>
You could then write the following jQuery code to check the parent checkbox when either of the children are checked:
$('input:checkbox.ckchild').click(function(event) {
var checked = $(this).is(':checked');
if (checked) {
$('#ckparent').attr('checked', true);
}
});
EDIT: The order in which the changed and clicked events are fired with regards to when the checked attribute is actually changed is dependent on the browser you are using -- which browsers are you targeting?