jQuery Select All Checkbox with toggleClass - javascript

I have seen other examples of this but have not successfully gotten this to function correctly. The examples I have seen also are just using regular checkboxes. I have used a class to stylize the checkbox with a sprite sheet so having a bit of trouble taking the ideas of these other examples and applying them to my case.
Here is the mark up:
<div id="showHideAll"">Show/Hide All<input type="checkbox" id="allCheck" name="pinSet" class="pinToggles" onclick="checkAllLinks()">
<label for="allCheck" class="css-label"></label></div>
</div>
<div>Opt1<input type="checkbox" id="opt1Check" name="pinSet" class="pinToggles" onclick="checkOpt1Links()">
<label for="opt1Check" class="css-label"></label>
</div>
<div>Opt2<input type="checkbox" id="opt2Check" name="pinSet" class="pinToggles" onclick="checkOpt2Links()">
<label for="opt2Check" class="css-label"></label>
</div>
<div>Opt3<input type="checkbox" id="opt3Check" name="pinSet" class="pinToggles" onclick="checkOpt3Links()">
<label for="dinShopCheck" class="css-label"></label>
</div>
The checked property is what changes the sprite using a css class.
input[type=checkbox].pinToggles:checked + label.css-label {
background-position: 0 -16px;
}
Most of this is for other functionality but thought I would show it just in case.
This is how I set up the individual checkboxes:
function checkOpt1Links(){
$('#opt1 li a').toggleClass("inactive");
if(opt1.getVisible() == true)
{
opt1.setOptions({visible:false});
}
else
{
opt1.setOptions({visible:true});
}
}
What I am looking for is the typical select all checkbox functionality, where if you check it the boxes all check, if you uncheck they all uncheck but also if you click a box when select all is checked the select all and the clicked checkbox uncheck and vice versa. I did look at this example: Jquery "select all" checkbox but just having difficult time making it work. Thanks for the help!

1) Use change event handler instead of click for checkbox and radio buttons.
You can make it simple like this
$('#showHideAll').on('change', 'input[type=checkbox]', function () {
if ($('.pinToggles').is(':checked')) {
$('.pinToggles').prop('checked', false)
}
else {
$('.pinToggles').prop('checked', true)
}
});
2) I have removed the class and onclick event handler in the below checkbox only.
HTML:
<div id="showHideAll">Show/Hide All<input type="checkbox" id="allCheck" name="pinSet" >
<label for="allCheck" class="css-label"></label></div>
</div>
Check this JSFiddle

Related

Bootstrap checkbox value passed correctly but not showed in the box

I have a frustrating issue since last week. I am using a bootstrap checkbox inside a modal that I want to prefill with either true or false depending on the user selection for that boolean field. Even though I can get the value correctly, I can not get the tick on the checkbox working.
modal.html
<div class="input-group">
<label class="form-check-label" for="active">
Active
<span>
<input class="form-check-input" name="activeCheckbox" type="checkbox" id="active" onclick="handleCheckboxClick()">
</span>
</label>
</div>
handleCheckboxClick.js
$('.form-check-input').change(function () {
var check = $(this).prop('checked');
if(check === true) {
$('#active').prop('checked', true);
} else {
$('#active').prop('checked', false);
}
});
jQuery that prefills the modal
$('#modal-edit-config').on('shown.bs.modal', function() {
$('#classname').focus();
var selectedId = confId;
$.ajax({
url: 'getConfig',
data: {configId: selectedId},
success: function(data){
var config = data;
if(config != null) {
$('#id').val(config.id);
$('#className').val(config.className);
console.log(config.active);
config.active ? $('#active').attr('checked', true).change() : $('#active').attr('checked', false).change();
}
},
error: function(result) {
alert("Error getting the audit configId");
}
});
});
I tried both with prop() and attr() but, it doesn't work.
The js function works perfectly fine but when the modal pops up the prefilled value of the checkbox even though it is correct, it is not corresponding to the tick or untick in the UI.
Checkboxes change their visual "checked" status based on the existence of the attribute name itself, not its setting -- according to dev.mozilla.org: checked, Boolean; if present, the checkbox is toggled on by default
<p>Checkbox checked="true"</p>
<input type="checkbox" checked="true">
<p>Checkbox checked="false"</p>
<input type="checkbox" checked="false">
<p>Checkbox (no checked attr)</p>
<input type="checkbox">
You should update your checkbox generation JS to leave out the attribute itself: $('#active').attr('checked', false) will show a checked checkbox.
For regular checkboxes
You should use the proper HTML semantics with .form-check wrapper as described in Forms > Checkboxes & Radios:
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck">
<label class="form-check-label" for="gridCheck">
Check me out
</label>
</div>
As such, our <input>'s and <label>'s are sibling elements as opposed to an <input> within a <label>. This is slightly more verbose as you must specify id and for attributes to relate the <input> and <label>.
For custom checkboxes
To point you in the right direction you should read the section Custom forms > checkboxes.
Please note a label and input pairing wrapped in a div comes with a specific order.
The input goes first and is not wrapped by the label.
The reason is simple once you realize an input is an HTML element and they do not support "pseudo elements" :before and :after. These "pseudo class selectors" are required to introduce custom design on checkboxes/radios and so on.
Trivial and simplified CSS selector:
input[type="checkbox"]:checked ~ label:before { content: '✓' }
Otherwise there's no direct solution to reverse this selector like label input[type="checkbox"]:checked.
With that said, HTML is capable of handling your states by itself. No need for the handleCheckboxClick.js. You can then use .prop() to select by default in the ajax handler.
If you need to change the order visualy, you can introduce something like .custom-checkbox-reverse.
.custom-checkbox-reverse .custom-control-label::before,
.custom-checkbox-reverse .custom-control-label::after {
left: auto;
right: -1.5rem;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet"/>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="customCheck1">
<label class="custom-control-label" for="customCheck1">Label after the checkbox</label>
</div>
<div class="custom-control custom-checkbox custom-checkbox-reverse">
<input type="checkbox" class="custom-control-input" id="customCheck2">
<label class="custom-control-label" for="customCheck2">Label before the checkbox</label>
</div>
FIDDLE to play around and enhance the padding for example as well.
A revision on the JavaScript part:
// what to expect here?
// should be sufficient to check if it has an id
// perhaps something else we can check? like config.status? Only you know at this point
// in fact it should always return the object or enter the error function
var checkboxState = false; // default
if(config && config.hasOwnProperty('id')) {
$('#id').val(config.id);
$('#className').val(config.className);
console.log(config.active); // expecting a boolean value
checkboxState = !!config.active; // double bang operator to make sure it's a boolean value
}
$('#active').prop('checked', checkboxState);

checkbox check one at a time not working in gridview

I have multiple checkboxes inside gridview
What i want is, if I select one checkbox and go to select another the first checkbox should get unchecked and second should get checked.
I tried below code
$('.chk').on('change', function () {
alert('click');
$('span.input.chk').not(this).prop('checked', false);
});
My browser rendered HTML for checkbox is below
<span class="chk" title="136"><input id="ContentPlaceHolder1_GrdInvoiceDetailsSearch_ob_GrdInvoiceDetailsSearchBodyContainer_ctl02_0_ctl00_0_ChkID_0" type="checkbox" name="ctl00$ContentPlaceHolder1$GrdInvoiceDetailsSearch$ob_GrdInvoiceDetailsSearchBodyContainer$ctl02$ctl02$ctl00$ChkID" /></span>
</div><div class="ob_gCd">136</div></div></td><td class="ob_gCW" style="width:25%;"><div class="ob_gCc1"><div class="ob_gCc2">GANDHI ADHIVITIYA COMBINE</div></div></td><td class="ob_gCW" style="width:25%;"><div class="ob_gCc1"><div class="ob_gCc2R">292700</div></div></td><td class="ob_gCW" style="width:25%;"><div class="ob_gCc1"><div class="ob_gCc2R">180</div></div></td><td class="ob_gCW ob_gC_Lc" style="width:21%;"><div class="ob_gCc1"><div class="ob_gCc2R">120</div></div></td></tr><tr class="ob_gRA"><td class="ob_gC ob_gC_Fc" style="width:4%;"><div class="ob_gCc1"><div class="ob_gCc2">
<span class="chk" title="102"><input id="ContentPlaceHolder1_GrdInvoiceDetailsSearch_ob_GrdInvoiceDetailsSearchBodyContainer_ctl02_1_ctl00_1_ChkID_1" type="checkbox" name="ctl00$ContentPlaceHolder1$GrdInvoiceDetailsSearch$ob_GrdInvoiceDetailsSearchBodyContainer$ctl03$ctl02$ctl00$ChkID" /></span>
kindly suggest how to achieve this
You will likely need to target the actual checkbox elements beneath your chk class as based on your markup, you are currently targeting the parent <span> elements :
// When one of your checkboxes is checked
$('.chk :checkbox').on('change', function () {
// Uncheck all of them that are not this
$('.chk :checkbox').not(this).prop('checked', false);
});
Use radio buttons, they have this behavior built-in.

Trying to create a checkbox for comparing elements

So far I manage to show/hide button when checkbox is checked but its checking all checkbox which I don't want.
my goal is to check different checkboxes without ticking all of them at the same time.
Edit: also to count how many elements have been checked.
http://jsfiddle.net/bLd0gaxy/1/
<input type="checkbox" class="compare" name="compare">
<label for="compare" class="compare-label ml-10"> Compare</label>
<!-- <div class="compare-btn"></div> -->
<button class="compare-btn ml-10" style="display: none;">Compare</button>
<input type="checkbox" class="compare" name="compare">
<label for="compare" class="compare-label ml-10"> Compare 2</label>
<!-- <div class="compare-btn"></div> -->
<button class="compare-btn ml-10" style="display: none;">Compare</button>
$('.compare').click(function() {
if($('.compare').is(':checked')){
$('.compare-label').hide();
$('.compare-btn').show();
} else{
$('.compare-label').show();
$('.compare-btn').hide();
}
});
You have to use .prop("checked") to get the checked state (http://api.jquery.com/prop/). Here is your working example: http://jsfiddle.net/infous/bLd0gaxy/3/
You need to use this to work with the closest elements:
$('.compare').change(function() {
if (this.checked) {
$(this).next("label").hide();
$(this).nextUntil("button").show();
} else {
$(this).next("label").show();
$(this).nextUntil("button").hide();
}
var totalChecked = $(".compare:checked").length;
});
Also, work with the change event of the checkbox.

Selected Checkbox disables the selection of another checkbox

I have a reason to use checkboxes instead of radio buttons so please don't suggest I use radio buttons but need to duplicate the functionality. However when I select the Yes checkbox, it disables the No checkbox for some reason. When no is selected I want to hide the div and deselect Yes, and the opposite when I select Yes I want to show the div and uncheck NO. The only way I can select NO when Yes is checked is to uncheck it.
Working demo Here
JS Fiddle not working Here
Javascript
function injure() {
if (document.getElementById("f2").checked == true) {
document.getElementById("LocFall").style.display="block";
document.getElementById("f1").checked = false;
} else {
if (document.getElementById("f1").checked == true) {
document.getElementById("LocFall").style.display="none";
document.getElementById("f2").checked = false;
}
}
}
CSS
#LocFall {
display:none;
}
HTML
<input type="checkbox" id="f1" name="" onclick="injure();">
<label for="f1"> No </label><BR>
<input type="checkbox" id="f2" name="" onclick="injure();">
<label for="f2"> Yes</label><BR>
<div id="LocFall">
Show some stuff
</div>
http://jsfiddle.net/6NN6s/14/
<input type="checkbox" id="f1" name="same" onclick="injure(this);" />
<label for="f1">No</label>
<BR>
<input type="checkbox" id="f2" name="same" onclick="injure(this);" />
<label for="f2">Yes</label>
<BR>
<div id="LocFall">Show some stuff</div>
function injure(cmb) {
if (cmb.checked) {
if(cmb.id==="f2")
{ document.getElementById("LocFall").style.display = "block";
document.getElementById("f1").checked = false;
}
else
{
document.getElementById("LocFall").style.display = "none";
document.getElementById("f2").checked = false;
}
}
}
try this out, may be what you need.
In Fiddle change on the left in second drop-down list 'onLoad' to 'no wrap - in <head>'.
Split injure into a different function for each; if you choose No, then you cannot choose Yes because of the way your function is set up - the first condition will always evaluate as true.
The problem stems from not knowing which checkbox was actually clicked inside the function. As it is there's only two different ways the function can respond: one if f1 is checked and one if f2 is checked. The problem is there's actually more possible states that you're trying to represent.
State 1: Nothing checked, user clicks f1 or f2
State 2: f1 checked, f2 clicked
State 3: f2 checked, f1 clicked
Your code handles the first state fine but it can't deal properly with the second ones. If you split your code into two seperate functions to handle each box then you'll have all the necessary information to write correct decision logic.
There's also the states of clicking the same box, but they are simple and your code handles them already.

CheckAll/UncheckAll checkbox with jQuery

I have made a check-box checkall/uncheckall.
HTML
<div> Using Check all function </div>
<div id="selectCheckBox">
<input type="checkbox" class="all" onchange="checkAll('selectCheckBox','all','check','true');" />Select All
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 1
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 2
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 3
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 4
</div>
main.js
function checkAll(parentId,allClass,checkboxClass,allChecked){
checkboxAll = $('#'+parentId+' .'+allClass);
otherCheckBox = $('#'+parentId+' .'+checkboxClass);
checkedCheckBox = otherCheckBox.filter($('input[type=checkbox]:checked'));
if(allChecked=='false'){
if(otherCheckBox.size()==checkedCheckBox.size()){
checkboxAll.attr('checked',true);
}else{
checkboxAll.attr('checked',false);
}
}else{
if(checkboxAll.attr('checked')){
otherCheckBox.attr('checked',true);
}else{
otherCheckBox.attr('checked',false);
}
}
}
It works fine. But get bulky when I have whole lot of checkboxes. I want to do same work by using jQuery rather than putting onchange on each checkbox. I tried different sort of things but couldnot work. I tried following one:
$('.check input[type="checkbox"]').change(function(e){
checkAll('selectCheckBox','all','check','true');
});
to do same work as onchange event but didnot work. Where do I went wrong.
I think you just need this: You do not need to pass all the arguments and have the inline onchange event attached to it. You can simplify your code.
$(function () {
$('input[type="checkbox"]').change(function (e) {
if(this.className == 'all')
{
$('.check').prop('checked', this.checked); //Toggle all checkboxes based on `.all` check box check status
}
else
{
$('.all').prop('checked', $('.check:checked').length == $('.check').length); // toggle all check box based on whether all others are checked or not.
}
});
});
Demo
Your selector is wrong:
.check input[type="checkbox"]
Above selects any input of type checkbox that has the ancestor with class .check. It'll match this:
<div class="check">
<input type="checkbox".../>
</div>
it should be:
input.check[type="checkbox"]
You closed the string here $('.check input[type='checkbox']') instead, you should use double quotes $('.check input[type="checkbox"]')

Categories