How to check if a checkbox is checked when programmatically added? [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 months ago.
Is there a way to check if a checkbox is checked when you programmatically add another checkbox? For example, if I have a function that adds a checkbox and then it's checked and then add another checkbox, the second checkbox determines if the first checkbox is selected or not. If the first checkbox is selected, don't show the second added checkbox. If the first checkbox is not selected, you can check the second checkbox and the first one is hidden.
The code I have below is suppose to hide any checkbox that's added after the first checkbox is selected.
$(document).on( "click", '.add', function() {
// programmatically add checkboxes
$('.add').after("<div id='cover_photo_set_featured'><input type='checkbox'></input>Set featured image</div><div class='add2'>+add</div>").remove();
});
$(document).on( "click", '.add2', function() {
$('.add2').after("<div id='cover_photo_set_featured'><input type='checkbox'></input>Set featured image</div>").remove();
});
// function to check is checkboxes are selected
if ($("#cover_photo_set_featured input").is(':checked')) {
$('#cover_photo_set_featured input[type=checkbox]').each(function() {
//Check if the box is checked
var x = $(this).is(':checked');
//if checkbox is NOT checked
if(x === false) {
//Hide the choice
$(this).parent().hide();
}
});
} else {
$('#cover_photo_set_featured input[type=checkbox]').parent().show();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="add">+add</div>

In javascript you can only add events to elements already on the DOM.
To achive what you want. you have to reassign events everytime you add a checkbox.
I would recommend adding a function that adds event listeners like so:
function setup() {
if ($("#cover_photo_set_featured input").is(':checked')) {
$('#cover_photo_set_featured input[type=checkbox]').each(function() {
//Check if the box is checked
var x = $(this).is(':checked');
//if checkbox is NOT checked
if(x === false) {
//Hide the choice
$(this).parent().hide();
}
});
} else {
$('#cover_photo_set_featured input[type=checkbox]').parent().show();
}
}
then calling it whenever you add a new checkbox.

Related

Remove checkbox background color on change using jquery

I have a simple quiz in which user can answer multiple questions, now when the user checks the box I am adding a class for the background.
Here is jsfiddle:demo
Here is function
// here we add event handler for newly created checkboxes.
nextQuestion.find("input[type='checkbox']").on('change', function () {
if ($(this).is(":checked")) {
//add checkbox background when is checked
$(this).addClass("input-before");
//uncheck the checkbox if another checkbox is checked
$('#next').prop("disabled", false);
$('input.cb').not(this).prop('checked', false, function(){
//remove the background ...this is not working
$(this).removeClass("input-before");
})
} else {
$('#next').prop("disabled", true);
$(this).removeClass("input-before");
}
});
Now when user check another checkbox the other checkbox is unchecked but the background is still there\
I want to remove the background when Unchecked.
what do I need to change to get this working?
You can iterate through checkbox to add and remove the background class as given below
nextQuestion.find("input[type='checkbox']").on('change', function () {
.....
$("input[type='checkbox']").each(function () {
if (this.checked) {
$(this).addClass("input-before");
}else{
$(this).removeClass("input-before");
}
});
......
});

Iterate over checkboxes array to determine if checked

I have a table with a "select all" checkbox. When I populate this table, all of the items that have been selected previously are checked. Currently, the "select all" checkbox will return checked even if not all of items are checked. I'm trying to create a function that will iterate over each checkbox, and if all are checked, then it will automatically toggle the select all checkbox. Same logic if not all items are selected - the select all checkbox will not be selected.
Here's the code I have so far:
function unclickSelectAll(parent) {
var $checkboxes = parent.find('input[type="checkbox"]');
var $selectAllCheckbox = $checkboxes.filter('.vendor');
var $invoiceCheckBoxes = $checkboxes.filter('.invoice');
$invoiceCheckBoxes.each(function(i, c) {
var checkbox = $(this);
if (checkbox[i].checked) {
$selectAllCheckbox.prop('checked', true);
} else {
$selectAllCheckbox.prop('checked', false);
}
});
};
What happens currently is that it will loop over the first checkbox, and if it's checked it will change the checked property of the select all check box to true. Then through the next loop I get an error that it cannot find the 'checked' property of checkbox[i];
you can do something like
$('.invoice:checkbox').click(function () {
unclickSelectAll();
});
function unclickSelectAll() {
var allSelected = $('.invoice:checked:checkbox').length === $('.invoice:checkbox').length;
$('.vendor:checkbox').prop('checked', allSelected);
}
plunker: http://plnkr.co/edit/iSrpfjd4Z7FUIhQkewcF?p=preview
You're switching the state of the select-all checkbox after testing each checkbox, so the final state will just be based on the last checkbox. You need to test whether all the checkboxes are checked. You can do this by simply counting the number of checkboxes and the number of checked checkboxes; if the count is the same, they're all checked.
if (parent.find(':checkbox').length == parent.find(':checkbox:checked').length) {
$selectallCheckbox.prop('checked', true);
} else {
$selectallCheckbox.prop('checked', false);
}

Select All Checkboxes while keeping track of manual selects jquery

I've been using a simple select all script for checkboxes for a while now that looks something like this:
<span id="select">Select All</span>
with
$('#select').click(function(event) {
var $that = $(this);
$('.checkbox').each(function() {
this.checked = $that.is(':checked');
});
});
It's fairly simple. It attaches to an onclick, loops through all the inputs with the class .checkbox and checks or unchecks them accordingly. However what I'd like to do now is make it a bit more user friendly adding the following functionality to it.
1) When the user click the link labeled "Select All" it should select all check boxes as normal, but then change the text to "Deselect All". Similarly, when the user clicks "Deselect All" the text would go back to "Select All".
2) If the users manually select all check boxes I'd like check for this scenario and update the text from Select All to Deselect All as well.
Your code is checking whether a <span> is :checked, which as far as I know is not possible. Perhaps I'm wrong, but in this answer I'll use a different approach to keeping track of that, a data attribute.
// initialize 'checked' property
$('#select').data('checked', false);
// make link control all checkboxes
$('#select').click(function(event) {
var $that = $(this);
var isChecked = ! $that.data('checked');
$that.data('checked', isChecked).html(isChecked ? 'Deselect All' : 'Select All');
$('.checkbox').prop('checked', isChecked);
});
// make checkboxes update link
$('.checkbox').change(function(event) {
var numChecked = $('.checkbox:checked').length;
if (numChecked === 0) {
$('#select').data('checked', false).html('Select All');
} else if (numChecked === $('.checkbox').length) {
$('#select').data('checked', true).html('Deselect All');
}
});
Not jquery, but here's what I'd do
var cb=document.getElementsByClassName('cb'); //get all the checkboxes
var selectAll=document.getElementById('selectAll'); //get select all button
function selectAllState(inputEle,selectAllEle){ //class to manage the states of the checkboxes
var state=1; //1 if button says select all, 0 otherwise;
var num=inputEle.length;
function allChecked(){ //see if all are checked
var x=0;
for(var i=0;i<num;i++){
if(inputEle[i].checked==true){
x+=1;
}
}
return x;
}
function handler(){ //if all checked or all unchecked, change select all button text
var y=allChecked()
if( y==num && state){
selectAllEle.innerHTML='Deselect All';
state=0;
} else if(y==0 && !state){
selectAllEle.innerHTML='Select All';
state=1;
}
}
for(var i=0;i<num;i++){
inputEle[i].addEventListener('change',handler); //listen for changes in checks
}
function checkAll(){ //function checks or unchecks all boxes
for(var i=0;i<num;i++){
inputEle[i].checked=state;
}
handler();
}
selectAll.addEventListener('click',checkAll); //listen for button click
}
var myState=new selectAllState(cb,selectAll); //instance the selectAllState class
This creates a javascript class to manage the states of all your checkboxes. It takes two arguments, the first being the array of checkboxes (which is what you get if you use getElementsByClassName), and the second being the select all button. The internal methods could be exposed using the this keyword if you want to be able to, for example, have a different part of the application select or deselect all the checkboxes.
Try breaking it down in several functions: Let's call the span toggle, as it can select and de-select all.
<span id="toggle">Select All</span>
And we'll have a function to select and de-select all of the values. No need to iterate through the list as prop sets the value for all elements
function SetAll(value){
$(".checkbox").prop("checked", value);
}
Then for the toggle button:
$("#toggle").click(function(){
if($(this).text() == "Select All"){
SetAll(true);
$(this).text("De-select All");
} else {
SetAll(false);
$(this).text("Select All");
}
});
Finally we need an onchange event for each checkbox:
$(".checkbox").change(function(){
var allCheckboxes = $(".checkbox");
var allChecked = $.grep(allCheckboxes, function(n,i){
return $(n).is(":checked");
}); //grep returns all elements in array that match criteria
var allUnchecked = $.grep(allCheckboxes, function(n,i){
return $(n)is(":checked");
},true); //invert=true returns all elements in array that do not match
// check the lengths of the arrays
if (allChecked.length == allCheckboxes.length)
$("#toggle").text("De-select All");
if (allUnchecked.length == allCheckboxes.length)
$("#toggle").text("Select All");
}):

Trigger functions from checkbox on click by clicking on a button

I have a couple of checkboxes and a button. When I click on checkbox - function is triggered. This is the desired behavior but I want to trigger it by clicking on the button. I want to have the possibility to first select checkboxes (I tried with return false and event.preventDefault but these completely switch the selection off) and then by clicking the button - trigger functions from checkboxes. Here is a link to jsfiddle:
http://jsfiddle.net/j93k2xns/6/
So for instance: I can select 3 checkboxes (nothing should happen) and after I click the button - three alerts should appear.
The code:
HTML:
<input type="checkbox" name='check[]' id="first">first</input>
<input type="checkbox" name='check[]'>second</input>
<input type="checkbox" name='check[]'>third</input>
<input type="checkbox" name='check[]'>fourth</input>
<input type="button" value="validate" id="val-button">
JS:
var check_state;
$(document).on('click','input[name="check[]"]', function(e){
if(check_state === true) {
alert('a');
} else {
return false;
}
});
$(document).on('click','#val-button', function(){
check_state = true;
});
There are a few interpretations to his question. If I'm reading it correctly, he wants to bind an arbitrary function to the checkboxes. Clicking the button should fire this event. This is how you can achieve that using custom events in jQuery:
$(function () {
$("input[name='check[]']").bind("myCustomButtonClick", function() {
if(this.checked) {
alert('a');
}
});
})
$(document).on('click','#val-button', function(){
$("input[name='check[]']").trigger("myCustomButtonClick");
});
And the associated jsfiddle: http://jsfiddle.net/3yf7ymos/
$(document).on('click','#val-button', function(){
$( 'input[name="check[]"]' ).each(function( index ) {
if($(this).is(':checked')) {
alert("a");
return true;
}
});
});
If you want to do something when the user checks a checkbox, add an event listener:
$('input[type="checkbox"]').click(function() {
if ($(this).is(':checked')) {
// do something
}
});
If the idea is run a couple of functions after the inputs are checked by clicking on a button:
function myFunction() {
if ($('input[id="something"]:checked').length == 0) {
// do something
} else if ($('input[id="something_2"]:checked').length == 0) {
// do something
}
//and so on..
}
$('#val-button').click(function() {
myFunction();
});
I have a similar inquiry. I have a number of check boxes. Each checkbox is linked to a different URL that opens a PDF form. I want my team to be able to select which forms they need by ticking the checkbox. Once they have done that, I would like a button to trigger the opening of each form based on which check box is checked. I have it so the checkbox upon being checked opens the form right away but it is very distracting. Its preferable they all get opened at once by a "button". Help. I am quite new to JavaScript so may need additional clarity.

Why isn't jquery detecting when a radio button is unchecked? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JQuery $(#radioButton).change(…) not firing during de-selection
I have the following HTML/jQuery:
<input id="rb1" type="radio" name="rb" checked="true">
<input id="rb2" type="radio" name="rb">
$("#rb2").change(function () {
if ($(this).is(":checked")) {
alert('checked');
}
else {
alert('unchecked');
}
});
When my rb2 radio button is unselected by selecting rb1, the change event does not fire. Why is this? Is it possible to get this working without changing my selector to match both inputs and then looking at the ID?
Fiddle: http://jsfiddle.net/4uRWR/
The change event only gets sent when you actually modify the item itself. When you click the other radio, you aren't modifying it. A fix would be to watch the change event on every input:radio, then just check the state of the relevant radio button:
$("input:radio").change(function () {
if ($("#rb2").is(":checked")) {
alert('checked');
}
else {
alert('unchecked');
}
});
http://codepen.io/AlienHoboken/pen/akwjB
Listen for change on every input related to your group of radios and then check if a specific one is selected.
$("input[name=rb]").change(function () {
if ($('#rb2').is(":checked")) {
alert('checked');
} else {
alert('unchecked');
}
});
http://jsfiddle.net/4uRWR/2/
You can artificially trigger a "change" on radio buttons from the same group so that the original bound handler would get picked up and output "unchecked". The trick is to avoid being stuck in an infinite loop by recursively re-triggering the event, we can avoid that by ignoring artificial events that lack the originalEvent property:
$("input[type=radio]").on("change", function (e) {
var $this = $(this);
//all inputs with the same name
var $targetInputSelector = $("input[name=" + $this.attr("name") + "]");
//check if the handler was fired "naturally"
//if yes, trigger the change handler "artificially" for inputs with the same name
if (e.hasOwnProperty('originalEvent')) {
//exclude the element that was changed "naturally"
//from the subset of all the elements with the same name
$targetInputSelector.not($this).triggerHandler("change");
}
});
This code works when added on top of your current handler and satisfies the without changing my selector to match both inputs and then looking at the ID criteria ;)
http://jsfiddle.net/a73tn/24/
I sorta ran into this issue a few days ago. Instead of listening for an individual click on a radio button, I listen for a click on the <ul> I have them in and then call this function to check if one has been selected.
// Iterate over the radio group and determine if one of them is selected
function loopRadBtns(btnGroup)
{
var isChecked = false;
btnGroup.find('input[type="radio"]').each(function()
{
if($(this).attr('checked'))
{
isChecked = true;
}
});
return isChecked;
}

Categories

Resources