Checkbox toggle all with jquery Trigger function - javascript

I am using a plugin that only triggers on click of checkbox , I need All button checkbox to existing code.
I have made it so that on click of ALL CHECKBOX I manually TRIGGER click selecting all checkbox and firing the existing jquery code
The problem comes when user clicks on one of checkbox I want that option to be as selected option so if all checkbox are checked (including the All) and user clicks on 3rd checkbox it should automatically select 3rd checkbox trigger click on all others (making them unchecked) including all
but my own conflicts i.e. my trigger clicks doesn't lets this happen and code gets into loop between All checkbox checked clicks and single checkbox click
I have created JS Fiddle.
In short I need toggle from checkbox button as well if all are selected on click on one of the checkbox it should make that one selected and rest all unselected
Here is the jQuery code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
jQuery(window).ready(function() {
//check ALl checkbox onClick
jQuery('body').on('click', '.chktaxoall,.chkcmfall',function (e) {
if(this.checked){
var i = 0;
var sList;
jQuery(this).closest('.togglecheck').find('input:checkbox').each(function () {
var sThisVal = (this.checked ? "1" : "0");
i++;
if(sThisVal==0 && i>1){
jQuery(this).trigger('click','bot');
}
});
}
else{
jQuery(this).closest('.togglecheck').find('input:checkbox').prop('checked', this.checked);
}
});
//IF ALL IS SELECTED but if a user clicks on a particular checkbox uncheck all except the one user checked
jQuery('body').on('click', '.wrap_acf input:checkbox',function (e) {
//if all is checked and someone unchecks a checkbox make all uncheck
var thisParent=jQuery(this).parents('.uwpqsf_class').attr('id');
var AllTicked =jQuery("#"+thisParent+" .chkcmfall").prop('checked');
if(thisParent && AllTicked){
jQuery("#"+thisParent+" .chkcmfall").prop('checked',false)
//jQuery(this).trigger('click');
}
})
});
</script>
Here is the HTML structure
<div id="mycategory" class="filter_acc_class uwpqsf_class togglecheck">
<h2 class="LabelPlaceHolder">Category</h2>
<!-- Add controlall and data-boxid -->
<label class="searchLabel control controlAll checkbox" data-boxid="wrap_id_cats"><input type="checkbox" class="chkcmfall" value="" name="mycatname[]" data-boxid="wrap_id_cats"><span class="control-indicator"></span>All</label>
<div id="wrap_id_cats" class="wrap_acf togglecheck">
<label class="searchLabel control checkbox"><input type="checkbox" value="16" name="mycatname[]"><span class="control-indicator"></span>Bakery<span class="fltr_num">(12)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="18" name="mycatname[]"><span class="control-indicator"></span>Indulgences<span class="fltr_num">(12)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="17" name="mycatname[]"><span class="control-indicator"></span>Dairy<span class="fltr_num">(7)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="19" name="mycatname[]"><span class="control-indicator"></span>Meat<span class="fltr_num">(7)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="27" name="mycatname[]"><span class="control-indicator"></span>test4<span class="fltr_num">(7)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="24" name="mycatname[]"><span class="control-indicator"></span>test1<span class="fltr_num">(5)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="26" name="mycatname[]"><span class="control-indicator"></span>test3<span class="fltr_num">(5)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="25" name="mycatname[]"><span class="control-indicator"></span>test2<span class="fltr_num">(1)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="29" name="mycatname[]"><span class="control-indicator"></span>test6<span class="fltr_num">(1)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="30" name="mycatname[]"><span class="control-indicator"></span>test7<span class="fltr_num">(1)</span></label>
</div>
</div>

Not sure I completely understand what you're asking, but with this script you can check/uncheck with one checkbox which reacts to changes of other checkboxes as well.
JavaScript:
$("input[type=checkbox]:not(.chkcmfall)").on("change", function () {
if ($(".chkcmfall").is(":checked")) {
$("input[type=checkbox]:not(this)").prop("checked", false);
$(this).prop("checked", true);
}
$(".chkcmfall").prop("checked", $("input[type=checkbox]:not(.chkcmfall):checked").length == $("input[type=checkbox]:not(.chkcmfall)").length);
});
$(".chkcmfall").on("change", function () {
$("input[type=checkbox]").prop("checked", $(this).is(":checked"));
});
What does it do?
It applies an eventhandler to all checkboxes except the one with class chkcmfall. Whenever one of these checkboxes change from checked to unchecked or vice versa, it counts all checked checkboxes (except the one with class chkcmfall) and if it matches the total amount of checkboxes, it checks the chkcmfall-checkbox as well. Otherwise it unchecks it.
When the chkcmfall-checkbox is checked, all other checkboxes are also checked.
EDIT: When the chkcmfall-checkbox is checked and then another checkbox is checked, only this latter one will be checked and the rest will be unchecked.
EDIT 2: Check all box now acts as a check/uncheck all box.
FIDDLE
EDIT 3: Added a new solution not to be using the prop attribute, but by using the click event of checkboxes as per request of the OP. I've made a difference between a click from a user and a click triggered by code by passing in an extra parameter in the trigger-function. This will prevent the infinite loops the OP was talking about, since we can now prevent the execution of triggering click events based on the source of the click.
JavaScript:
jQuery(window).ready(function () {
//check ALl checkbox onClick
jQuery('body').on('click', '.chktaxoall,.chkcmfall', function (e, source) {
var all = $(this).is(":checked");
if (source != "code") {
$("input[type=checkbox]:not(this)").each(function () {
if ($(this).is(":checked") != all)
$(this).trigger("click", "code");
});
}
});
jQuery('body').on('click', '.wrap_acf input:checkbox', function (e, source) {
var allChecked = $(".chkcmfall").is(":checked");
if (source != "code" && allChecked) {
$(".wrap_acf input:checkbox:not(this)").trigger("click", "code");
$(".chkcmfall").trigger("click", "code");
} else if (source != "code") {
if ($(".wrap_acf input:checkbox:checked").length == $(".wrap_acf input:checkbox").length)
$(".chkcmfall").trigger("click", "code");
}
})
});
NEW FIDDLE
Edit 4: Updated the answer to reflect the wishes of OP to be able to have multiple sets of checkboxes.
For this approach to work you have to be able to set data--attributes to both the checkboxes and the (un)select-all-checkbox. In the following example, the script only applies the checking/unchecking of checkboxes based on a data-attribute called set.
$(document).ready(function () {
//check ALl checkbox onClick
$("body").on("click", ".chktaxoall,.chkcmfall", function (e, source) {
var all = $(this).is(":checked");
var set = $(this).data("set");
if (source != "code") {
$("input[type=checkbox][data-set='" + set + "']:not(this)").each(function () {
if ($(this).is(":checked") != all)
$(this).trigger("click", "code");
});
}
});
$("body").on("click", ".wrap_acf input:checkbox", function (e, source) {
var set = $(this).data("set");
var allChecked = $(".chkcmfall[data-set='" + set + "']").is(":checked");
if (source != "code" && allChecked) {
$(".wrap_acf input[type=checkbox][data-set='" + set + "']:not(this)").trigger("click", "code");
$(".chkcmfall[data-set='" + set + "']").trigger("click", "code");
}
else if (source != "code")
{
if ($(".wrap_acf input[type=checkbox][data-set='" + set + "']:checked").length == $(".wrap_acf input[type=checkbox][data-set='" + set + "']").length)
$(".chkcmfall[data-set='" + set + "']").trigger("click", "code");
}
})
});
FIDDLE 3

supposing you have a table with un checkbox (A) (with class: checkall) as part of a header. then all elements in this column are CHECKBOXES (B) (with class: checkitem ) then you want to change the state of all checkboxes (B) (the checked will be unchecked and vice-versa):
$(".checkall").click(function() {
var value = $(this).is(':checked');
$('.checkitem:checkbox').each(function(){this.checked = !this.checked;})
});

I'm not sure I follow, but here's a simple script to uncheck all checkboxes after a checkbox has been checked:
EDIT: realized you're looking to check/uncheck with one specific checkbox.
$('.chkcmfall').click(function(){
var chall = this;
$('input:checkbox').attr('checked',$(chall).attr('checked');
});
EDIT 2: accounting for your comment:
$('input:checkbox').click(function(){
var clicked_box = this
// see if all checkboxes are checked
if($('input:checked').length == $('input:checkbox').length){
$('input:checkbox').attr('checked','false');
$(clicked_box).attr('checked'),'true');
}
});

Related

Creating a check and uncheck all function in Angular Js

I have few check boxes which I have been check already using ng-init
<div class="checkbox">
<label>
<input type="checkbox" ng-init="model.A='A'" ng-model="model.A" ng-true-value="'A'" ng-false-value="'nope'"/>A
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-init="model.A='B'" ng-model="model.B" ng-true-value="'B'" ng-false-value="'nope'"/>B
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-init="model.C='C'" ng-model="model.C" ng-true-value="'C'" ng-false-value="'nope'"/>C
</label>
</div>
What I want is to create a function to make these check boxes check and uncheck when I check a seperate check box, link or a button. Can some one help me?
Its simple as below,
create a link to toggle the checkboxes check status, Here i have created three links
first one is for toggle the checkbox status, second one for uncheck all the checkboxes and last one for check all the checboxes.
toggle check | uncheck all | check all
click on uncheck will be handle like below,
$scope.uncheckAll = function() {
$scope.model.A = false;
$scope.model.B = false;
$scope.model.C = false;
};
assign a value which result in uncheck of the checkboxes.
click on check all will be handle like below,
$scope.checkAll = function() {
$scope.model.A = 'A';
$scope.model.B = 'B';
$scope.model.C = 'C';
};
Assign the initial values that result in check status of the checkboxes.
Toggle check like below, if A unchecked then all gonna uncheck other vice all are gonna check.
$scope.toggleCheck = function() {
if ($scope.model.A == false) {
$scope.checkAll();
} else {
$scope.uncheckAll();
}
};
here is a DEMO
//on button click
var key;
for(key in $scope.model){
if(//checked condition){
$scope.model[key] = key;
}else{
$scope.model[key] = 'nope';
}
}

Radio button clicks change function

We have two radio buttons when we change the button need to call function. Below is my code.
<input id="ordertype" type="radio" align="top" name="ordertype" value="NEW ORDER" checked="">
<input id="ordertype" type="radio" align="top" name="ordertype" value="ADDITIONAL ORDER (add items to previous order)">
Jquery code
jQuery(document).ready(function(){
$('input:radio[name="ordertype"]').change(function(){
if($(this).val() === 'ADDITIONAL ORDER (add items to previous order)'){
var removepages = 'boothlightingDiv';
}else{
var removepages = 'furnishingsprovidedDiv';
}
});
});
Call function ToggleDiv('boothsizeDiv', removepages);
Based radio button need to change the ToggleDiv function parameter.Any help?
I would do something like this:
http://jsfiddle.net/bobrierton/5Lc17p1t/1/
$(document).on('change', 'input[name=ordertype]', function() {
var value = $(this).val();
if (value == "ADDITIONAL ORDER (add items to previous order)") {
//whatever your trying to do
var removepages = 'boothlightingDiv';
}else{
//or whatever your trying to do
var removepages = 'furnishingsprovidedDiv';
}
alert(removepages)
});
instead of $(this) use $('input:radio[name="order type"]:checked') to access the one that is checked, because when one changes, they both change.

Radio button value change onclick

I want to get value from radio button by onclick and I will use this value for sql query.
What should I do for this?
I want when I click on radio button I will get the value of the button and this value will work for sql query to change data or information
I use php and mysql.
<td><input type="radio" name="ac" value="AC"/>AC</td>
<td><input type="radio" name="ac" value="Non AC" />Non AC</td>
First, note that you shouldn't use tabular elements for non-tabular data. But it makes sense using label element, and use change event instead of click.
<div id="wrapper">
<label><input type="radio" name="ac" value="AC"/>AC</label>
<label><input type="radio" name="ac" value="Non AC" />Non AC</label>
</div>
To get the value, you can use event delegation:
document.getElementById('wrapper').onchange = function(e) {
/* Maybe you should also check: e.target.type==='radio' */
if(e.target.tagName.toLowerCase() === 'input') {
var value = e.target.value;
/* do something */
}
};
Demo
Another possibility is creating an event listener for each radio:
var els = document.getElementById('wrapper').getElementsByTagName('input'),
handler = function() {
var value = this.value;
/* do something */
};
for(var i = 0; i<els.length; ++i) {
els[i].onchange = handler;
}
Demo

How can I toggle radiobutton

Say this is my HTML:
<input type="radio" name="rad" id="Radio0" checked="checked" />
<input type="radio" name="rad" id="Radio1" />
<input type="radio" name="rad" id="Radio2" />
<input type="radio" name="rad" id="Radio4" />
<input type="radio" name="rad" id="Radio3" />
As you can see the 1st radio button is checked. I need the radio button to function like toggle. For eg. If I again click on radio0, all radio buttons should be unchecked.
How can I achieve that?
Update: I don't want any extra buttons. For eg. I could add a button and set the checked property for all radio buttons to be false. However, I don't want that. I only want my form to consist of these 4 radio buttons.
Update: Since most of the people don't understand what I want, let me try to rephrase- I want the radio button to function in toggle mode. I've given the same name to all radio buttons hence it's a group. Now I want the radiobuttons to toggle itself. Eg. if I click on radio0, it should get unchecked if it's checked and checked if it's unchecked.
The problem you'll find is that as soon a radio button is clicked its state is changed before you can check it. What I suggest is to add a custom attribute to keep track of each radio's previous state like so:
$(function(){
$('input[name="rad"]').click(function(){
var $radio = $(this);
// if this was previously checked
if ($radio.data('waschecked') == true)
{
$radio.prop('checked', false);
$radio.data('waschecked', false);
}
else
$radio.data('waschecked', true);
// remove was checked from other radios
$radio.siblings('input[name="rad"]').data('waschecked', false);
});
});
You will also need to add this attribute to the initially checked radio markup
<input type="radio" name="rad" id="Radio0" checked="checked" data-waschecked="true" />
See demo here : http://jsfiddle.net/GoranMottram/VGPhD/2/
Once you give the name of 2 or more radio buttons as the same, they automatically become a group. In that group only one radio button can be checked. You have already achieved this.
This code solved my issue
$("[type='radio']").on('click', function (e) {
var previousValue = $(this).attr('previousValue');
if (previousValue == 'true') {
this.checked = false;
$(this).attr('previousValue', this.checked);
}
else {
this.checked = true;
$(this).attr('previousValue', this.checked);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label >Toogle radio button example</label>
<br />
<input type="radio" name="toogle_me" value="mango"> Blue </input>
<input type="radio" name="toogle_me" value="kiwi"> Green </input>
<input type="radio" name="toogle_me" value="banana"> Yellow </input>
<input type="radio" name="toogle_me" value="orange"> Orange </input>
I use an onClick() like the following for my custom radios:
$(function(){
// if selected already, deselect
if ($(this).hasClass('selected') {
$(this).prop('checked', false);
$(this).removeClass('selected');
}
// else select
else {
$(this).prop('checked', true);
$(this).addClass('selected');
}
// deselect sibling inputs
$(this).siblings('input').prop('checked', false);
$(this).siblings('input').removeClass('selected');
}
Using #Goran Mottram answer just tweaking it a bit to suit the case where radio buttons are not siblings.
$(".accordian-radio-button").click(function(){
var wasChecked = true;
if($(this).data('waschecked') == true){
$(this).prop('checked', false);
wasChecked = false;
}
$('input[name="ac"]').data('waschecked', false);
$(this).data('waschecked', wasChecked);
})
<input class="accordian-radio-button" data-waschecked="false" type="radio" name="ac" id="a1" />
I ran into this as well, after thinking about it and playing around with the various fiddles offered, I had a few dissatisfactions with the offered solutions.
My main problem was the last line of the accepted answer, requiring a reset:
// remove was checked from other radios
$radio.siblings('input[name="rad"]').data('waschecked', false);
And since I'm not using jQuery, I'd have to loop over and evaluate the siblings myself, which isn't a huge deal, but seemed inelegant to me. But, there's no way around it with that method, because you're using the dataset as a storage of information.
After playing around, I realized is that the problem is that when a radio is clicked, it triggers the clicked event, and whatever function is attached to that click event completes itself before the function for the "onchange" event is ever evaluated, let alone called. So, if the click event "unchecks" the toggle, then no change event is ever fired.
I've left my failed attempt here:
https://codepen.io/RiverRockMedical/pen/daMGVJ
But, if you could answer the question "will a change event happen after this click event?" then you could get a toggle working.
The solution I came up with can be seen at this pen:
https://codepen.io/RiverRockMedical/pen/VgvdrY
But basically is as follows:
function onClick(e) {
e.dataset.toDo = 'uncheck';
setTimeout(uncheck, 1, {
event:'click',
id:e.id,
dataset:e.dataset
});
}
So, on the click event, set a marker that the click has happened, and the use setTimeout() to create a pause that allows the onchange event to be evaluated and fire.
function onChange(e) {
e.dataset.toDo = 'leave';
}
If the onchange event fires, it undoes what was done by the onclick event.
function uncheck(radio) {
log('|');
if (radio.event !== 'click') return;
log('uncheck');
if (radio.dataset.toDo === 'uncheck') {
document.getElementById(radio.id).checked = false;
radio.checked = false;
}
}
Then, when the uncheck function starts, it has the information of whether a change event followed the click event or not. If not, then the radio is unchecked, and functions as a toggle.
And, it's basically self-resetting, so I don't have to loop over all the radios and reset their datasets to the initial values at the end of the function.
Now, I'm sure there's a cooler async/await way to do this that doesn't use setTimeout and would be even more elegant, but I'm still learning and I couldn't come up with it. Anyone else?
<input type="radio" name="gender" id="male"onclick="getChecked(1)"><label for="male">Male</label>
<input type="radio" name="gender" id="female"onclick="getChecked(2)"><label for="female">female</label>
<script>
var btnChecked = "";
function getChecked(i) {
if(btnChecked == i) {
btnChecked = "";
document.getElementsByTagName("input")[i-1].checked = false;
}
else btnChecked = i;
}
</script>
A simple approach in jQuery (even though I don't use jQuery nowdays):
function makeRadioInputsToggleable(radioInputs){
let radioGroup = {
lastValue: radioInputs.filter(':checked').prop('value'),
get value(){
return this.lastValue;
},
set value(v){
let inputToCheck = radioInputs.filter((i, el) => el.value === v);
radioInputs.filter(':checked').prop('checked', false);
if(inputToCheck.length > 0){
inputToCheck.prop('checked', true);
this.lastValue = v;
}else{
this.lastValue = undefined;
}
},
};
radioInputs.on('click', (e) => {
let input = e.target;
if(input.value === radioGroup.lastValue){
input.checked = false;
radioGroup.lastValue = undefined;
}else{
radioGroup.lastValue = input.value;
}
}).on('keydown', (e) => {
if(e.code === 'Space'){
let input = e.target;
if(input.checked){
input.checked = false;
input.blur();
radioGroup.lastValue = undefined;
}
}
});
return radioGroup;
}
let radioInputs = $('input[type="radio"][name="rad"]');
let radioGroup = makeRadioInputsToggleable(radioInputs);
$('.check-radio').on('click', (e)=>{
let value = e.target.value;
radioGroup.value = value;
});
// Note:
// 1. pass a single group of radio inputs to `makeRadioInputsToggleable`
// 2. set distinct values for each radio input in a group.
// 3. to change checked radio programmatically, use `radioGroup.value = 'XXX'` rather than radioInputs.prop('checked', false).filter('[value="XXX"]').prop('checked', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>makeRadioInputsToggleable</h3>
<label><input type="radio" name="rad" value="1" id="Radio0" checked="checked" />1</label>
<label><input type="radio" name="rad" value="2" id="Radio1" />2</label>
<label><input type="radio" name="rad" value="3" id="Radio2" />3</label>
<label><input type="radio" name="rad" value="4" id="Radio4" />4</label>
<label><input type="radio" name="rad" value="5" id="Radio3" />5</label>
<p>1. click on an already-checked radio button, the radio will be toggled to unchecked.</p>
<p>2. focus on an already-checked radio button and press 'Space', the radio will be toggled to unchecked. <i>(This may not work in Code Snippet result area)</i></p>
<p>
3. programmatically
<button class="check-radio" value="2">check radio with value 2</button>
<button class="check-radio" value="10">check radio with value 10</button>
</p>

How to check radio button is checked using JQuery?

I have two radio buttons in one group, I want to check the radio button is checked or not using JQuery, How ?
Given a group of radio buttons:
<input type="radio" id="radio1" name="radioGroup" value="1">
<input type="radio" id="radio2" name="radioGroup" value="2">
You can test whether a specific one is checked using jQuery as follows:
if ($("#radio1").prop("checked")) {
// do something
}
// OR
if ($("#radio1").is(":checked")) {
// do something
}
// OR if you don't have ids set you can go by group name and value
// (basically you need a selector that lets you specify the particular input)
if ($("input[name='radioGroup'][value='1']").prop("checked"))
You can get the value of the currently checked one in the group as follows:
$("input[name='radioGroup']:checked").val()
//the following code checks if your radio button having name like 'yourRadioName'
//is checked or not
$(document).ready(function() {
if($("input:radio[name='yourRadioName']").is(":checked")) {
//its checked
}
});
This is best practice
$("input[name='radioGroup']:checked").val()
jQuery 3.3.1
if (typeof $("input[name='yourRadioName']:checked").val() === "undefined") {
alert('is not selected');
}else{
alert('is selected');
}
Radio buttons are,
<input type="radio" id="radio_1" class="radioButtons" name="radioButton" value="1">
<input type="radio" id="radio_2" class="radioButtons" name="radioButton" value="2">
to check on click,
$('.radioButtons').click(function(){
if($("#radio_1")[0].checked){
//logic here
}
});
Check this one out, too:
$(document).ready(function() {
if($("input:radio[name='yourRadioGroupName'][value='yourvalue']").is(":checked")) {
//its checked
}
});
Taking some answers one step further - if you do the following you can check if any element within the radio group has been checked:
if ($('input[name="yourRadioNames"]:checked').val()){ (checked) or if (!$('input[name="yourRadioNames"]:checked').val()){ (not checked)
Try this:
var count =0;
$('input[name="radioGroup"]').each(function(){
if (this.checked)
{
count++;
}
});
If any of radio button checked than you will get 1
Simply you can check the property.
if( $("input[name='radioButtonName']").prop('checked') ){
//implement your logic
}else{
//do something else as radio not checked
}

Categories