jquery uncheck and check and vise versa checkbox of child element - javascript

Here is my html
#This will be generated throught loop
<li class="selector">
<a>
<input type="checkbox" value="test" /> test
</a>
</li>
Here is my jquery click event
$('.selector').on('click', function() {
if($(this).find('input').is(':checked')){
#uncheck the checkbox
}else{
#check the checkbox
}
});
How do I uncheck if checked and check if unchecked

Try
$(document).on('click', '.selector', function (e) {
if (!$(e.target).is('input')) {
$(this).find('input').prop('checked', function () {
return !this.checked;
});
}
});
Demo: Fiddle
Another way
$(document).on('click', '.selector', function (e) {
$(this).find('input').prop('checked', function () {
return !this.checked;
});
});
$(document).on('click', '.selector input', function (e) {
e.stopPropagation();
});
Demo: Fiddle

Try this
$('.selector').on('click', function() {
var checkbox = $(this).find(':checkbox');
if($(checkbox).is(':checked')){
$(checkbox).prop('checked', false);
}else{
#check the checkbox
$(checkbox).prop('checked', true);
}
});

I don't understand why you are trying to do this with JavaScript. If the user clicks directly on the checkbox it will automatically check/uncheck itself, but if you add code to check/uncheck it in JS that would cancel out the default behaviour so in your click handler you'd need to test that the click was elsewhere within the .selector.
Anwyay, the .prop() method has you covered:
$('.selector').on('click', function(e) {
if (e.target.type === "checkbox") return; // do nothing if checkbox clicked directly
$(this).find("input[type=checkbox]").prop("checked", function(i,v) {
return !v; // set to opposite of current value
});
});
Demo: http://jsfiddle.net/N4crP/1/
However, if your goal is just to allow clicking on the text "test" to click the box you don't need JavaScript because that's what a <label> element does:
<li class="selector">
<label>
<input type="checkbox" value="test" /> test
</label>
</li>
As you can see in this demo: http://jsfiddle.net/N4crP/2/ - clicking on the text "test" or the checkbox will toggle the current value without any JavaScript.

Related

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.

How to stop event bubbling in jquery?

I'm using some JQ stuff on check box, even if the parent div is clicked. I am toggling the value of check box. Clicking on div is working perfectly but when you click on checkbox the function is called twice. Is there any way to solve this problem? following is my code(Fiddle)
HTML:
<div class="check-unit">
<input type="checkbox" class="check" />
<p class="brandList">Model</p>
</div>
JQ:
$('.check').on('change',function(e){
e.stopImmediatePropagation();
if($(this).is(':checked')){
console.log("checked");
}else{
console.log("unchecked");
}
});
$('.check-unit').on('click',function(e){
var checkbox = $(this).children('.check'),
chhhk= checkbox.attr('checked') ? false : true;
checkbox.attr('checked',chhhk);
$(this).children('.check').change();
});
I've seen eventbubbling problem on stackoverflow, but still confused how to do this. FIDDLE
Only execute the callback on the parent element if the target is not the input
$('.check').on('change',function(e){
if(this.checked){
console.log("checked");
}else{
console.log("unchecked");
}
});
$('.check-unit').on('click',function(e){
if ( ! $(e.target).hasClass('check')) {
$(this).children('.check').prop('checked', function(_,state) {
return !state;
}).trigger('change');
}
});
FIDDLE
As a sidenote, this is what label elements are for!
You need to use .prop() instead of .attr() to set the checked property.
$('.check').on('change', function (e) {
if (this.checked) {
console.log("checked");
} else {
console.log("unchecked");
}
}).click(function (e) {
//prevent clicks in the checksboxes from bubbling up otherwise when you click on the checkbox the state will get toggled again the event will be bubbled to check-unit which will again toggle the state negating the click
e.stopPropagation()
});
$('.check-unit').on('click', function () {
var checkbox = $(this).children('.check'),
//use .is() and checked-selector to check whether the checkbox is checked
chhhk = checkbox.is(':checked');
//use .prop() instead of .attr() & toggle the checked state
checkbox.prop('checked', !chhhk).change();
});
Demo: Fiddle
You can check if you are clicking the checkbox before changing.
$('.check-unit').on('click', function (e) {
if (!($(e.target).hasClass('check'))) {
var checkbox = $(this).children('.check'),
chhhk = checkbox.prop('checked');
checkbox.prop('checked', !chhhk).change();
}
});
Also note that the code is using prop instead of attr because when you are using boolean attribute values you should use .prop()
DEMO

How to bind to a click to toggle a checkbox?

Given a list of LIs each LI includes a checkbox like so:
<li class="contact">
<input type="checkbox" class="checkbox" name="checkableitems[]" value="1333">
<div class="content">
<cite>Baby James</cite>
</div>
</li>
I would like to be able to toggle the checkbox on LI click, not just on checkbox click. I got this work which you can see here:
http://jsfiddle.net/xgB5X/2/
The problem is, while clicking on the LI toggles the checkbox, click on the checkbox directly is no broken. Clicking on the checkbox no longer toggles. Any suggestions to get this working? Thanks
Why not using label tags?
<li class="contact">
<input id='input1' type="checkbox" class="checkbox" name="checkableitems[]" value="1333">
<label for='input1'>Baby James</label>
</li>
DEMO
http://jsfiddle.net/xgB5X/3/ Check this.
I've added a little bit of code to stop the propagation. This will prevent the event to reach to the li tag.
$('input[type=checkbox]').on('click', function(e) {
e.stopPropagation();
});
Your problem was when the checkbox was clicked it was changing its state, but when the event reach to the li tag as it contains the check box once again it was changing its state.
A couple of notes:
use .prop() instead of .attr() (it's also easier to tell true/false on it, must each other through all browsers.
You can check the e.srcElement for your classname of checkbox within the click().
$('.listview li').on('click', function(e) {
if (e.srcElement.className === 'checkbox') {
e.stopPropagation();
return;
}
checkbox = $(this).find(':checkbox');
// Toggle Checkbox
if (checkbox.prop('checked')) {
checkbox.prop('checked', false);
} else {
checkbox.prop('checked', true);
}
});
jsFiddle
You can try something like this jsFiddle
$('.listview li > *').children().bind({
click: function(e) {
checkbox = $(this).closest('li').find('.checkbox');
checkbox.attr('checked', !checkbox.is(':checked'));
}
});​
$('.listview li').on('click', function(e) {
var c = $('.checkbox', this);
c.prop('checked', !c[0].checked);
}).find('.checkbox').on('click', function(e) {e.stopPropagation();});​​​​​
FIDDLE
Even though I think you should use a label for this here is method working
$('.listview li').bind({
click: function(e) {
var checkbox = $(this).find('.checkbox').get(0);
if (e.target == checkbox) return;
checkbox.click();
}
});
FIDDLE

Javascript/ JQuery Deselecting radio buttons

I have the following javascript, which I want to use to enable the user to deselect a selected radio button by clicking it. (I know this is not standard, but it is required by the system :)
DeselectRadioButton = {
setup: function () {
$(".deselectRadioButton").click(function () {
if ($(this).is(':checked')) {
alert("I am checked!");
($(this).removeAttr('checked'));
}
});
}
};
My issue is that when I select an unselected radio button, it immediately deselects it after the alert shows.
I guess I am receiving the event after the item has changed - how can I fix this code to make my radio button deselectable?
Thanks!
However, the main issue is that when I
select an unselected radio button, it
immediately deselects it after the
alert shows.
It seems you can't prevent the default behavior of a radio button with either return false or e.preventDefault() as the radio button always is checked when the click handler is fired. One way around this was to add a separate class to the radio button and use that as your indicator.
$(".deselectRadioButton").click( function(e){
if($(this).hasClass("on")){
$(this).removeAttr('checked');
}
$(this).toggleClass("on");
}).filter(":checked").addClass("on");
Code example on jsfiddle.
One of the challenges I found while doing this was with groups of radio buttons. The solutions provided work splendidly for a single radio button, but in groups I ran into an issue where de-selecting one and then trying to select another failed (until a second click).
I just came across a solution here that's working splendidly:
var allRadios = $('input[type=radio]')
var radioChecked;
var setCurrent = function(e) {
var obj = e.target;
radioChecked = $(obj).attr('checked');
}
var setCheck = function(e) {
if (e.type == 'keypress' && e.charCode != 32) {
return false;
}
var obj = e.target;
if (radioChecked) {
$(obj).attr('checked', false);
} else {
$(obj).attr('checked', true);
}
}
$.each(allRadios, function(i, val){
var label = $('label[for=' + $(this).attr("id") + ']');
$(this).bind('mousedown keydown', function(e){
setCurrent(e);
});
label.bind('mousedown keydown', function(e){
e.target = $('#' + $(this).attr("for"));
setCurrent(e);
});
$(this).bind('click', function(e){
setCheck(e);
});
});
try:
$(this).removeAttr('checked');
I experienced the same problem David described with groups of radio buttons. Here's another way around that problem (based on Mark's solution) that works for multiple radio button groups on the same page:
$(":radio").click( function(e){
var itsOn = $(this).hasClass("on");
$(":radio[name="+ this.name + "]").removeClass("on");
if(itsOn){
$(this).removeAttr('checked');
$(this).siblings().filter("[value='']").attr('checked', true);
} else {
$(this).addClass("on");
}
}).filter(":checked").addClass("on");
Are you sure there's nothing else messing with it?
I tried this code, and it works:
HTML
<ul>
<li>
<input id="one" name="value" type="radio">
<label for="one">One</label>
</li>
<li>
<input id="two" name="value" type="radio">
<label for="two">Two</label>
</li>
<li>
<input id="three" name="value" type="radio">
<label for="three">Three</label>
</li>
</ul>
JavaScript
$("input[type='radio']").click(function(event) {
// If the button is selected.
if ($(this).hasClass("checked")) {
// Remove the placeholder.
$(this).removeClass("checked");
// And remove the selection.
$(this).removeAttr("checked");
// If the button is not selected.
} else {
// Remove the placeholder from the other buttons.
$("input[type='radio']").each(function () {
$(this).removeClass("checked");
});
// And add the placeholder to the button.
$(this).addClass("checked");
}
});
You can test it here.

jquery select all checkboxes

I have a series of checkboxes that are loaded 100 at a time via ajax.
I need this jquery to allow me to have a button when pushed check all on screen. If more are loaded, and the button is pressed, to perhaps toggle all off, then pressed again toggle all back on.
This is what i have, obviously its not working for me.
$(function () {
$('#selectall').click(function () {
$('#friendslist').find(':checkbox').attr('checked', this.checked);
});
});
The button is #selectall, the check boxes are class .tf, and they all reside in a parent div called #check, inside a div called #friend, inside a div called #friendslist
Example:
<div id='friendslist'>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr1'>
</div>
</div>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr2'>
</div>
</div>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr3'>
</div>
</div>
</div>
<input type='button' id='selectall' value="Select All">
I know I'm revisiting an old thread, but this page shows up as one of the top results in Google when this question is asked. I am revisiting this because in jQuery 1.6 and above, prop() should be used for "checked" status instead of attr() with true or false being passed. More info here.
For example, Henrick's code should now be:
$(function () {
$('#selectall').toggle(
function() {
$('#friendslist .tf').prop('checked', true);
},
function() {
$('#friendslist .tf').prop('checked', false);
}
);
});
$('#friendslist .tf')
this selector will suit your needs
Use the jquery toggle function. Then you can also perform whatever other changes you may want to do along with those changes... such as changing the value of the button to say "check all" or "uncheck all".
$(function () {
$('#selectall').toggle(
function() {
$('#friendslist .tf').attr('checked', 'checked');
},
function() {
$('#friendslist .tf').attr('checked', '');
}
);
});
A very simple check/uncheck all without the need of loop
<input type="checkbox" id="checkAll" /> Check / Uncheck All
<input type="checkbox" class="chk" value="option1" /> Option 1
<input type="checkbox" class="chk" value="option2" /> Option 2
<input type="checkbox" class="chk" value="option3" /> Option 3
And the javascript (jQuery) accounting for "undefined" on checkbox value
** UPDATE - using .prop() **
$("#checkAll").change(function(){
var status = $(this).is(":checked") ? true : false;
$(".chk").prop("checked",status);
});
** Previous Suggestion - may not work **
$("#checkAll").change(function(){
var status = $(this).attr("checked") ? "checked" : false;
$(".chk").attr("checked",status);
});
OR with the suggestion from the next post using .prop() combined into a single line
$("#checkAll").change(function(){
$(".chk").attr("checked",$(this).prop("checked"));
});
This is how I toggle checkboxes
$(document).ready(function() {
$('#Togglebutton').click(function() {
$('.checkBoxes').each(function() {
$(this).attr('checked',!$(this).attr('checked'));
});
});
});
maybe try this:
$(function () {
$('#selectall').click(function () {
$('#friendslist .tf').attr('checked', this.checked);
});
});
<div class="control-group">
<input type="checkbox" class="selAllChksInGroup"> All
<input type="checkbox" value="NE"> Nebraska
<input type="checkbox" value="FL"> Florida
</div>
$(document).ready(function(){
$("input[type=checkbox].selAllChksInGroup").on("click.chkAll", function( event ){
$(this).parents('.control-group:eq(0)').find(':checkbox').prop('checked', this.checked);
});
});
I could not get this last example to work for me. The correct way to query the state of the checkbox is apparently :
var status = $(this).prop("checked");
and not
var status = $(this).attr("checked") ? "checked" : false;
as above.
See jQuery receiving checkbox status
It works for me (IE, Safari, Firefox) by just changing your this.checked to 'checked'.
$(function() {
$('#selectall').click(function() {
$('#friendslist').find(':checkbox').attr('checked', 'checked');
});
});
You may try this:
$(function () {
$('#selectall').click(function () {
$('#friendslist input:checkbox').attr('checked', checked_status);
});
});
//checked_status=true/false -as the case may be, or set it via a variable
assuming #selectall is a checkbox itself whose state you want copied to all the other checkboxes?
$(function () {
$('#selectall').click(function () {
$('#friendslist input:checkbox').attr('checked', $(this).attr('checked'));
});
});
try this
var checkAll = function(){
var check_all = arguments[0];
var child_class = arguments[1];
if(arguments.length>2){
var uncheck_all = arguments[2];
$('#'+check_all).click(function (){
$('.'+child_class).attr('checked', true);
});
$('#'+uncheck_all).click(function (){
$('.'+child_class).attr('checked', false);
});
$('.'+child_class).click(function (){
var checkall_checked = true;
$('.'+child_class).each(function(){
if($(this).attr('checked')!=true){
checkall_checked = false;
}
});
if(checkall_checked == true){
$('#'+check_all).attr('checked', true);
$('#'+uncheck_all).attr('checked', false);
}else{
$('#'+check_all).attr('checked', false);
$('#'+uncheck_all).attr('checked', true);
}
});
}else{
$('#'+check_all).click(function (){
$('.'+child_class).attr('checked', $(this).attr('checked'));
});
$('.'+child_class).click(function (){
var checkall_checked = true;
$('.'+child_class).each(function(){
if($(this).attr('checked')!=true){
checkall_checked = false;
}
});
$('#'+check_all).attr('checked', checkall_checked);
});
}
};
To "check all" and "uncheck all" is same checkbox
checkAll("checkall_id", "child_checkboxes_class_name");
To "check all" and "uncheck all" is separate checkbox
checkAll("checkall_id", "child_checkboxes_class_name", "uncheckall_id");
Here is how I achieved it.
function SelectAllCheckBoxes();
{
$('#divSrchResults').find(':checkbox').attr('checked', $('#chkPrint').is(":checked"));
}
The following fires the above line.
<input type=checkbox id=chkPrint onclick='SelectAllCheckBoxes();' />
On the click of chkPrint , every checkbox in the grid divSrchResults' is either checked or unchecked depending on the status of chkPrint.
Of course, if you need advanced functions like unchecking the titled checkbox when every other checkbox has been unchecked, you need to write another function for this.
I created a function that I use on all projects. This is just the initial draft, but maybe it will help:
Function:
function selectAll(wrapperAll, wrapperInputs) {
var selectAll = wrapperAll.find('input');
var allInputs = wrapperInputs.find('input');
console.log('Checked inputs = ' + allInputs.filter(':not(:checked)').length);
function checkitems(allInputs) {
//If all items checked
if (allInputs.filter(':not(:checked)').length === 0) {
console.log('Function: checkItems: All items checked');
selectAll.attr('checked', true);
} else {
console.log('Function: checkItems: Else all items checked');
selectAll.attr('checked', false);
}
}
checkitems(allInputs);
allInputs.on('change', function () {
checkitems(allInputs)
});
selectAll.on('change', function () {
if (this.checked) {
console.log('This checkbox is checked');
wrapperInputs.find(':checkbox').attr('checked', true);
} else {
console.log('This checkbox is NOT checked');
wrapperInputs.find(':checkbox').attr('checked', false);
}
});
}
It accepts the 2 parameters where the inputs are wrapped into and you cand use-it like this:
$(function () {
var wrapperAll = $('.selectallinput');
var wrapperInputs = $('.inputs');
selectAll(wrapperAll, wrapperInputs);
});
See demo: http://jsfiddle.net/cHD9z/
So "checked" is a crappy attribute; in many browsers it doesn't work as expected :-( Try doing:
$('#friendslist').find(':checkbox')
.attr('checked', this.checked)
.attr('defaultChecked', this.checked);
I know setting "defaultChecked" doesn't make any sense, but try it and see if it helps.
<input type="checkbox" onclick="toggleChecked(this.checked)"> Select / Deselect All
Now here are two versions of the toggleChecked function dependent on the semantics of your document. The only real difference is the jQuery selector for your list checkboxes:
1: All checkboxes have a class of “checkbox” (<input type=”checkbox” class=”checkbox” />)
function toggleChecked(status) {
$(".checkbox").each( function() {
$(this).attr("checked",status);
})
}
2: All the checkboxes are contained within a div with an arbitary id:
<div id="checkboxes">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
In this case the function would look like this:
function toggleChecked(status) {
$("#checkboxes input").each( function() {
$(this).attr("checked",status);
})
Have fun!
This may work for both (checked/unchecked) selectall situations:
$(document).ready(function(){
$('#selectall').click(function () {
$("#friendslist .tf").attr("checked",function(){return $(this).attr("checked") ? false : true;});
});
});
The currently accepted answer won't work for jQuery 1.9+. The event handling aspect of the (rather heavily) overloaded .toggle() function was removed in that version, which means that attempting to call .toggle(function, function) will instead just toggle the display state of your element.
I'd suggest doing something like this instead:
$(function() {
var selectAll = $('#selectall');
selectAll.on('click', function(e) {
var checked = !(selectAll.data('checked') || false);
$('#friendslist .tf').prop('checked', checked);
selectAll.data('checked', checked);
});
});
That uses a regular click event handler, plus a data attribute to track the "toggled" status and invert it with each click.
Here's a basic jQuery plugin I wrote that selects all checkboxes on the page, except the checkbox/element that is to be used as the toggle. This, of course, could be amended to suit your needs:
(function($) {
// Checkbox toggle function for selecting all checkboxes on the page
$.fn.toggleCheckboxes = function() {
// Get all checkbox elements
checkboxes = $(':checkbox').not(this);
// Check if the checkboxes are checked/unchecked and if so uncheck/check them
if(this.is(':checked')) {
checkboxes.prop('checked', true);
} else {
checkboxes.prop('checked', false);
}
}
}(jQuery));
Then simply call the function on your checkbox or button element:
// Check all checkboxes
$('.check-all').change(function() {
$(this).toggleCheckboxes();
});
As you are adding and removing more checkboxes via AJAX, you may want to use this instead of .change():
// Check all checkboxes
$(document).on('change', '.check-all', function() {
$(this).toggleCheckboxes();
});

Categories

Resources