jQuery checking checkboxes does not work - javascript

I'm trying to implement a "Select All" checkbox on an HTML form using JQuery 1.9.1. As far as I can tell, it should be as simple as using .prop to check or uncheck a checkbox, but nothing I try seems to work.
Please see below for what I have tried, I've commented out some failed attempts out and I cannot get this to work for even one checkbox. What is the correct way to do this? Am I missing something, possibly in the HTML?
HTML
<input type="checkbox" id="cb_select_all" name="cb_select_all" value="t" />
<label for="cb_select_all"><b>Select All</b>
</label>
<br />
<input type="checkbox" name="cb1" id="cb1" class="cb_all" value="t" />
<label for="cb1">1 test</label>
<br />
<input type="checkbox" name="cb2" id="cb2" class="cb_all" value="t" />
<label for="cb2">2 test</label>
Javascript
$(document).ready(function () {
$("#cb_select_all").change(cb_select_all_onchange);
}); //end $(document).ready
function cb_select_all_onchange() {
if ($("#cb_select_all").checked) {
//$("#cb1").prop("checked", true);
//$(".cb_all").each(function(){ this.checked = true; });
//document.getElementById("cb1").checked = true;
$(".cb_all").prop("checked", true);
} else {
$("#cb1").prop("checked", false);
}
}
http://jsfiddle.net/mLnb5qed/5/
Thanks,
jdt

Change your if to this
if ($("#cb_select_all")[0].checked) { }
( or ) if ($("#cb_select_all").is(":checked")) { }
The problem is the first one is a property of native element and not jQuery object. Accessing it by an index gives you the ability to use that property. The second way is the jQuery way.

Use
$("#cb_select_all").is(':checked');

This worked for me:
$(document).ready(function () {
$("#cb_select_all").change(function () {
if ($("#cb_select_all").prop("checked") == true) {
$('.cb_all').prop('checked', true);
}
else {
$('.cb_all').prop('checked', false);
}
});
});
What happens:
Check if the "cb_select_all" checkbox changes state
if the "checked" state is set to true
check all "cb_all" checkboxes
else
uncheck all "cb_all" checkboxes

Related

Issue with script being triggered by wrong checkbox

I'm trying to enable/disable a place order button based on whether or not the terms acceptance checkbox has been checked. The script I have been working on works fine for that, but it's also triggered when a different checkbox (with a different id) is checked. Although the other checkbox enables the button, it doesn't disable it again when un-checking it. So I think it's something wrong with the 'on change' part.
I've tried everything I could find and can't make it work only when the checkbox with id 'terms' is checked:
<script>
jQuery(window).on('load',function(){
setTimeout(function(){
jQuery('#payment #place_order').attr("disabled","disabled");
},1000);
});
jQuery(document).on('change','#terms',function() {
var ischecked = document.getElementById("terms");
if(ischecked.checked == false){
jQuery('#payment #place_order').attr("disabled","disabled");
}else{
jQuery('#payment #place_order').removeAttr("disabled");
}
});
</script>
The terms checkbox is as below:
<input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox ios-switch" name="terms" id="terms">
And the other one that triggers it is as below:
<input class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" id="createaccount" type="checkbox" name="createaccount" value="1">
Your code is not clear.
Assuming the place order has the id of #place_order, there is no need to add the container
jQuery(function() { // on page load
jQuery('#place_order').attr("disabled", "disabled");
jQuery(document).on("change", "#terms", function() { // assuming the terms is dynamically inserted
if (!this.checked) {
jQuery('#place_order').attr("disabled", "disabled");
} else {
jQuery('#place_order').removeAttr("disabled");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Terms <input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox ios-switch" name="terms" id="terms"><br/>
<button id="place_order">Place order</button>
<hr/>
Create account <input class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" id="createaccount" type="checkbox" name="createaccount" value="1">

selecting all or some parent / child checkboxes in a styled format

First of all: http://jsfiddle.net/1q5st19f/
I have a checkbox group where if all the child checkboxes (countries) are checked, the parent checkbox (region) becomes checked as well. Likewise, if the parent checkbox is unchecked, the child checkboxes should be unchecked, too. I found a script that worked perfectly until I styled the checkboxes with prettyCheckable (from http://arthurgouveia.com/prettyCheckable/).
If I remove prettyCheckable, it works. If I add it, it's correctly styled but won't work anymore. What am I doing wrong? I tried to rename the classes but that didn't work either.
The basic markup is like
<fieldset>
<input type="checkbox" class="parentCheckBox" /> Africa
<div class="content">
<input type="checkbox" value="1" name="cntrs[]" class="childCheckBox" data-label=""> Algeria<br />
<input type="checkbox" value="2" name="cntrs[]" class="childCheckBox" data-label=""> Angola<br />
<input type="checkbox" value="3" name="cntrs[]" class="childCheckBox" data-label=""> Benin<br />
</div>
</fieldset>
prettyCheckable made this a bit tricky. It says in the documentation that you can use $('#myInput').prettyCheckable('check'); but I could not get it to work. So I just used the anchors class checked instead to determine if the checkbox is checked.
This may not be the most pretty implementation but it's working. You should make the code more modular an maybe reconsider some of the choices I quickly made.
First I removed the childCheckBox from the HTML and initialized prettyCheckable with options, so I could get the class to the wrapper div:
// make childCheckboxes prettyCheckable
$('.content input:checkbox').each(function () {
$(this).prettyCheckable({
// add this class to the wrapper div created by prettyCheckable
customClass: "childCheckBox"
});
});
Same with the parentCheckbox:
// make parentCheckBox prettyCheckable
$('input:checkbox.parentInput').prettyCheckable({
// add this class to the wrapper div created by prettyCheckable
customClass: "parentCheckBox"
});
I also changed childCheckBox click event to do the functionality you wanted
//clicking the last unchecked or checked checkbox should check or uncheck the parent checkbox
$('.childCheckBox').click(function () {
var $parentAnchor = $(this).parents('fieldset:eq(0)').find('.parentCheckBox a');
var $childAnchors = $(this).parents('fieldset:eq(0)').find('.childCheckBox a');
var $thisAnchor = $(this).find('a');
var parentIsChecked = $parentAnchor.hasClass('checked');
var thisIsChecked = $thisAnchor.hasClass('checked');
var isLastOne = true;
// loop through all childCheckBoxes and determine if this is the last one checked or unchecked
$childAnchors.each(function (index) {
if ((!thisIsChecked && $(this).hasClass('checked'))
|| (thisIsChecked && !$(this).hasClass('checked'))) {
isLastOne = false;
}
});
// if the childCheckBox was the last one, change the state of the parentCheckBox
if (isLastOne && thisIsChecked) {
$parentAnchor.addClass('checked');
} else if (isLastOne && !thisIsChecked) {
$parentAnchor.removeClass('checked');
}
});
I was pretty tired when forking this, so I hope I didn't do any stupid mistakes. If you have any questions about the code, please ask.
Fiddle: http://jsfiddle.net/1q5st19f/17/
This took me forever to debug. There were a number of issues most importantly of which was that you are using a very backlevel version of prettyCheckable. However, after changing to the latest level and starting again, I have a fully working solution for you. See this jsFiddle.
I started again from the beginning but here is the code:
HTML
<fieldset>
<div class="group">
<input type="checkbox" class="parentCheckBox" data-label="Africa"/>
<div class="content">
<input type="checkbox" value="1" class="childCheckBox" data-label="Algeria" />
<br />
<input type="checkbox" value="2" class="childCheckBox" data-label="Angola" />
<br />
<input type="checkbox" value="3" class="childCheckBox" data-label="Benin" />
<br />
</div>
</div>
</fieldset>
JavaScript
$(function () {
$('input:checkbox').each(function () {
$(this).prettyCheckable();
});
$(".parentCheckBox").change(function (e) {
var checked = $(this).prop("checked");
$(".childCheckBox", $(this).closest(".group")).each(function (i, e) {
$(e).prettyCheckable(checked?"check":"uncheck");
});
});
$(".childCheckBox").change(function(e) {
var checkedCount = unCheckedCount = 0;
$(e.currentTarget).closest(".content").find(".childCheckBox").each(function(i,e2) {
if ($(e2).prop("checked")) {
checkedCount++;
} else {
unCheckedCount++;
}
});
if (unCheckedCount == 0) {
$(e.currentTarget).closest(".group").find(".parentCheckBox").prettyCheckable("check");
} else {
$(e.currentTarget).closest(".group").find(".parentCheckBox").prettyCheckable("uncheck");
}
});
});
I'll be delighted to answer any questions you may have.
The semantics of checking or unchecking all children could have an alternate solution shown in this jsFiddle. It talks to when the parent checkbox should be checked or unchecked as a function of the children.
What prettyCheckable does behind the scenes, is it hides the checkboxes and adds an a tag to the page, and updates the hidden checkboxes when the a tag is clicked. The a tag also gets a style of checked when the checkbox is checked. There appears to be a bug though, that the checked class is not added to or removed from the a tag when the state of the checkboxes is manipulated through code. Anyway, your JavaScript was correctly updating the state of the checkboxes, but prettyCheckable wasn't detecting that and failed to update its classes.
Anyway, I rewrote your script so all the logic is handled in 1 event handler, and I included a work-around for the prettyCheckable bug, but I left your HTML alone so you should only have to replace your JavaScript code. See below for a runnable example:
$('input:checkbox').prettyCheckable();
$("input:checkbox").on("change", function() {
var checkbox = $(this);
var parent = checkbox.closest("fieldset");
if (checkbox.hasClass("parentCheckBox")) {
//this is a parent, check or uncheck all children
var isChecked = checkbox.is(":checked");
//add checked attribute in the DOM and add the class for prettyCheckable on all children
parent.find("input.childCheckBox:checkbox").prop("checked", isChecked).each(function() {
if (isChecked)
$(this).next("a").addClass('checked');
else
$(this).next("a").removeClass('checked');
});
} else {
//this is a child, check or uncheck the parent
var parentCheckbox = parent.find("input.parentCheckBox:checkbox");
var isChecked = !parent.find("input.childCheckBox:checkbox").get().some(function(item) {
return !$(item).is(":checked");
});
//add the checked attribute to the dom and add the class for prettyCheckable
parentCheckbox.prop("checked", isChecked);
if (isChecked)
parentCheckbox.next("a").addClass('checked');
else
parentCheckbox.next("a").removeClass('checked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://qfuse.com/js/utils/prettyCheckable/prettyCheckable.js"></script>
<link href="http://arthurgouveia.com/prettyCheckable/js/prettyCheckable/dist/prettyCheckable.css" rel="stylesheet"/>
<fieldset>
<input type="checkbox" class="parentCheckBox" /> Africa
<div class="content">
<input type="checkbox" value="1" name="cntrs[]" class="childCheckBox" data-label="" /> Algeria<br />
<input type="checkbox" value="2" name="cntrs[]" class="childCheckBox" data-label="" /> Angola<br />
<input type="checkbox" value="3" name="cntrs[]" class="childCheckBox" data-label="" /> Benin<br />
</div>
</fieldset>

HTML checkbox handling

So I have a group of checkboxes like this:
[x] No stuff
[ ] Stuff 1
[ ] Stuff 2
[ ] Stuff 3
When any of the stuff checkboxes are clicked, I want the "No Stuff" one automatically deselected. Also, I would like everything to be deselected if "No stuff" gets selected.
Can someone point me in the right direction? Thanks.
Give some similar ids to the stuff check boxes - like "chkStuff1", "chkStuff2", "chkStuff3"
and give one onclick function to each like - onclick = "StuffClicked(this);" - same for all.
Lets say, the No Stuff check box has an id - "chkNoStuff"
then try this code -
function StuffClicked(chkBoxObj) {
var isNoStuffChecked = true;
if($('#chkBoxObj').is(':checked')) {
$('#chkNoStuff').prop('checked', false);
}
else {
$('[id^="chkStuff"]').each(function(){
if($(this).is(':checked')) {
isNoStuffChecked = false;
break;
}
});
}
$('#chkNoStuff').prop('checked', isNoStuffChecked );
}
$('#chkNoStuff').unbind('click').bind('click', function(){
$('[id^="chkStuff"]').each(function(){
$(this).prop('checked', false);
});
});
Hope this helps
Fiddle: WORKING DEMO
<label><input type="checkbox" class="jsNoStuff" /> No Stuff</label><br />
<label><input type="checkbox" class="jsStuff" /> Stuff 1</label><br />
<label><input type="checkbox" class="jsStuff" /> Stuff 2</label><br />
<label><input type="checkbox" class="jsStuff" /> Stuff 3</label><br />
<label><input type="checkbox" class="jsStuff" /> Stuff 4</label><br />
<script type="text/javascript">
jQuery(function ($) {
var $jsNoStuff = $('.jsNoStuff');
var $jsStuff = $('.jsStuff');
var fClickStuff = function () {
$jsNoStuff.prop('checked', false);
};
var fClickNoStuff = function () {
if ($jsNoStuff.is(':checked')) {
$jsStuff.prop('checked', false);
}
};
$jsNoStuff.click(fClickNoStuff);
$jsStuff.click(fClickStuff);
});
</script>
Use This
<input type="checkbox" id="all" />
<input type="checkbox" class="a" />
<input type="checkbox" class="a" />
<input type="checkbox" class="a" />
jquery
jQuery('#all').click(function(){
var that =$(this);
jQuery('.a').each(function(v){
if (that.is(':checked')){
$(this).attr('disabled', true);
}else{
$(this).attr('disabled', false);
}
});
})
click here for see
This should do what you need:
$('input[name="noStuff"]').change(function () {
if ($(this).is(":checked")) $('input[name^="stuff"]').prop('checked', false)
})
$('input[name^="stuff"]').change(function () {
$('input[name="noStuff"]').prop('checked', !$('input[name^="stuff"]:checked').length)
});
jsFiddle example
If you give them all the same class, you can uncheck the first with ordinal 0 when any of the others are clicked.
You can also uncheck/check options by looping through the collection and setting the properties. This is the easy way to check or uncheck multiple options.
How to uncheck a group of checkboxes when another checkbox is checked
Check/Uncheck checkbox with javascript?

jQuery click event on radio button doesn't get fired

I've got the following code to trigger a click event on some radio buttons! but it doesn't get fired! can any one help me with this!
CODE :
$("#inline_content input[name='type']").click(function(){
if($('input:radio[name=type]:checked').val() == "walk_in"){
$('#select-table > .roomNumber').attr('enabled',false);
}
});
RADIO BUTTONS
<form class="type">
<input type="radio" name="type" checked="checked" value="guest">In House</input>
<input type="radio" name="type" value="walk_in">Walk In</input>
</form>.
Update
Tried onChange() too but not working.
It fires. Check demo http://jsfiddle.net/yeyene/kbAk3/
$("#inline_content input[name='type']").click(function(){
alert('You clicked radio!');
if($('input:radio[name=type]:checked').val() == "walk_in"){
alert($('input:radio[name=type]:checked').val());
//$('#select-table > .roomNumber').attr('enabled',false);
}
});
There are a couple of things wrong in this code:
You're using <input> the wrong way. You should use a <label> if you want to make the text behind it clickable.
It's setting the enabled attribute, which does not exist. Use disabled instead.
If it would be an attribute, it's value should not be false, use disabled="disabled" or simply disabled without a value.
If checking for someone clicking on a form event that will CHANGE it's value (like check-boxes and radio-buttons), use .change() instead.
I'm not sure what your code is supposed to do. My guess is that you want to disable the input field with class roomNumber once someone selects "Walk in" (and possibly re-enable when deselected). If so, try this code:
HTML:
<form class="type">
<p>
<input type="radio" name="type" checked="checked" id="guest" value="guest" />
<label for="guest">In House</label>
</p>
<p>
<input type="radio" name="type" id="walk_in" value="walk_in" />
<label for="walk_in">Walk in</label>
</p>
<p>
<input type="text" name="roomnumber" class="roomNumber" value="12345" />
</p>
</form>
Javascript:
$("form input:radio").change(function () {
if ($(this).val() == "walk_in") {
// Disable your roomnumber element here
$('.roomNumber').attr('disabled', 'disabled');
} else {
// Re-enable here I guess
$('.roomNumber').removeAttr('disabled');
}
});
I created a fiddle here: http://jsfiddle.net/k28xd/1/
Personally, for me, the best solution for a similar issue was:
HTML
<input type="radio" name="selectAll" value="true" />
<input type="radio" name="selectAll" value="false" />
JQuery
var $selectAll = $( "input:radio[name=selectAll]" );
$selectAll.on( "change", function() {
console.log( "selectAll: " + $(this).val() );
// or
alert( "selectAll: " + $(this).val() );
});
*The event "click" can work in place of "change" as well.
Hope this helps!
A different way
$("#inline_content input[name='type']").change(function () {
if ($(this).val() == "walk_in" && $(this).is(":checked")) {
$('#select-table > .roomNumber').attr('enabled', false);
}
});
Demo - http://jsfiddle.net/cB6xV/
Seems like you're #inline_content isn't there! Remove the jQuery-Selector or check the parent elements, maybe you have a typo or forgot to add the id.
(made you a jsfiddle, works after adding a parent <div id="inline_content">: http://jsfiddle.net/J5HdN/)
put ur js code under the form html or use $(document).ready(function(){}) and try this.
$('#inline_content input[type="radio"]').click(function(){
if($(this).val() == "walk_in"){
alert('ok');
}
});

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