Jquery Exclude a checkbox from select all - javascript

My HTML code to select all checkboxes
Select All <input type="checkbox" name='select_all' id='select_all' value='1'/>
My Javascript code to select all checkboxes
<script type="text/javascript">
$('#select_all').change(function() {
var checkboxes = $(this).closest('form').find(':checkbox');
if($(this).is(':checked'))
{
checkboxes.prop('checked', true);
} else {
checkboxes.prop('checked', false);
}
});
</script>
The code works great and selects all the checkboxes, I would like to exclude the following checkbox from the selection (select all) criteria, is it possible to exclude the following?
<input type="checkbox" name='sendtoparent' id='sendtoparent' value='1'/>

Try using the not method:
$(this).closest('form').find(':checkbox').not('#sendtoparent');

Firstly you can use :not or not() to exclude the element by its id attribute. From there you can simplify the logic by just setting the checked property of those checkboxes to match that of the #select_all element. Try this:
$('#select_all').change(function() {
var $checkboxes = $(this).closest('form').find(':checkbox').not('#sendtoparent');
$checkboxes.prop('checked', this.checked);
});

Related

jQuery toggle checkbox and also toggle anchor text

I have a checkbox as follows:
<div class="left-col">
.......
<div class="actors-top sel-actors">
<p class="selall sel-actors"><a class="sel-actors" id=""seltext>Select all Actors</a></p>
<input type="checkbox" name="" value="" class="chk1" class="sel-actors" />
</div>
.......
</div>
I want the whole space of the div sel-actors control the checkbox checked and not checked. When Select all Actors is clicked I want all checkboxes on the left-col to be checked and the text Select all Actors to be changed into Deselect all Actors. On the click back i want it to go back to how it was.
After checking out stackoverflow i found something that checks the checkbox but doesnt toggle text with it:
$(document).ready(function() {
$(".sel-actors").click(function() {
var checkBoxes = $(".left-col input");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
});
});
I would like this to toggle text also.
Here is what you want.
$(document).ready(function() {
var SEL_ACTORS_TEXT = {
CHECKED: 'Deselect all Actors',
UNCHECKED: 'Select all Actors'
};
$(".sel-actors").click(function() {
var checkBoxes = $(".left-col input"),
$this = $(this);
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
if ($this.prop('checked')) {
$this.text(SEL_ACTORS_TEXT.CHECKED);
} else {
$this.text(SEL_ACTORS_TEXT.UNCHECKED);
}
});
});
Basically, add a variable to store the potential text strings and then after updating the checkboxes, set the string accordingly.
Hope this helps!
Try this:
$('.sel-actors').text('Deselect all Actors');
EDIT: to incorporate it into your function, do this:
$(document).ready(function() {
$(".sel-actors").click(function() {
var checkBoxes = $(".left-col input");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
if($('chk1').is(':checked'))
$(this).text('Deselect all Actors');
else
$(this).text('Select all Actors');
});
});
EDIT #2: note that you have defined the class property twice for your checkbox; try either merging them or maybe setup chk1 as an id instead, then you'd call it like this: $('#chk1'). You may also want to add an id for your anchor holding the text to differentiate it from the checkbox; modify the function accordingly, of course.
EDIT #3: Here is the cleaned up code:
$(document).ready(function() {
$("#chk1").click(function() {
var checkBoxes = $(".left-col input");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
if($(this).is(':checked'))
$('#seltext').text('Deselect all Actors');
else
$('#seltext').text('Select all Actors');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="sel-actors" id="seltext">Select all Actors</a>
<input type="checkbox" name="" value="" id="chk1" class="sel-actors" />
Try the following.
<script type="text/javascript">
$('.sel-actors').click(function (event) {
if (this.checked) {
$('.chk1').each(function () {
$('.sel-actors').val("De-select all Actors");
this.checked = true;
});
} else {
$('.chk1').each(function () {
$('.sel-actors').val("Select all Actors");
this.checked = false;
});
}
});
</script>

How to check 2 checkboxes that have the same name

So I have a ajax search form which gives results with a checkbox:
Here is part of PHP code for each search result:
<input type="checkbox" class="lovkrav_checkbox checkbox_search" name="lovkrav['.$lovkrav_id.']" value="'.$lovkrav_id.'" orig-id="lovkrav'.$lovkrav_id.'" id="lovkravs'.$lovkrav_id.'" '.$checked.'/>
and there is a twin checkbox already on website with the same name but with different id.
By using "orig-id" property I am getting the id of the twin checkbox. Both checkboxes have same class lovkrav_checkbox.
I came to the point where the click event is detected by the twin checkbox as it should but not the checkbox you clicked on!
Here is the code:
$(document).on("click",".lovkrav_checkbox",function(e){
toggle_id = document.getElementById($(this).attr("orig-id"));
$(toggle_id).trigger("click");
});
What I want to achieve is when a user clicks on one checkbox - the twin checkbox (the one with same name property) will be checked/unchecked as well.
What am I doing wrong?
Would be easier to toggle the checked state with vanilla javascript.
HTML
<input type="checkbox" name="test">
<input type="checkbox" name="test">
JS
//All of the checkboxes
var $checkboxes = $("input[type=checkbox][name=test]");
//The event handler
$checkboxes.on("click", function() {
//Get the state of the check box you clicked
var checkedState = this.checked
//Make it the state of all the checkboxes
$checkboxes.each(function() {
this.checked = checkedState;
});
});
Here is the fiddle
You can try this:
DEMO
$(document).on("click",".check",function(e){
$("."+this.className).prop("checked", this.checked);
});
Try this too:
js:
$(document).on("click",".lovkrav_checkbox",function(e){
toggle_id = $(this).attr("name");
isChecked = $(this).prop("checked");
$("input:checkbox").each(
function(){
if($(this).attr("name") == toggle_id && isChecked){
$(this).prop("checked",true);
}
else{
$(this).prop("checked",false);
}
});
});
fiddle
Try this
$("input[type=checkbox][name=test]").prop("checked",true);

How to disable the other items in a checkboxlist when one of them is selected using Javascript

i am using a checkbox list in a form.
i have multiple options in the checkbox list.
When one of the option is checked then other options should be disabled so that users should not be allowed to select other options.
i have done it in c# in the eventhandler but i cannot use postback anymore
how can we do this in javascript or jquery
foreach (ListItem li in chk_mycheckbox.Items)
{
if ((!(li.Text.ToString().Contains("Unknown"))))
{
li.Enabled = false;
}
}
Might you actually want a set of radio buttons instead.
e.g.
<li><input type="radio" name="gender" value="male">Male</li>
<li><input type="radio" name="gender" value="female">Female</li>
As it will enforce only one selection.
However, in your current scenario you could use the following lines to loop over the checkboxes and disable any that are not selected. (this is using jquery 1.6+)
$('input[type=checkbox]').each(function () {
if(!$(this).is(':checked')){
//if not checked
$(this).prop('disabled', true);
}
});
Following on from your comment.
Give the tick boxes that should disable the others an extra class e.g. "single-selection". Then your code can look something like this:
$(document).ready(function() {
$('#formId input.single-selection').on('click', function (e) {
var selectedCheckbox = $(this);
if(selectedCheckbox.is(':checked')){
$('#formId input[type=checkbox]').each(function () {
if(selectedCheckbox[0] != $(this)[0]){
//if not selected checkbox
$(this).prop('disabled', true);
$(this).attr('checked', false);
}
});
}else{
$('#formId input[type=checkbox]').prop('disabled', false);
}
});
});
I've not tested it, but I believe this is what you need. Just replace the ids and classes with what you're using.
Assuming you want the other options to become enabled if the user deselects the selected option, you could try this code. The code assumes that your form has an ID of 'form1'
$('#form1 input').on('click',function(evt){
var clickedEl = evt.target;
if(clickedEl.checked){
$('#form1 input').each(function(){
$(this).attr('disabled',true);
});
$(clickedEl).attr('disabled',false);
}
else{
$('#form1 input').each(function(){
$(this).attr('disabled',false);
});
}
});
Note that in jquery, the each function allows you to pass it a function that will be called on each element matched by the selector.
Here is a jsfiddle with the code working: http://jsfiddle.net/vvt5g/
Agree with Andrew's answer, that is the functionality of radio buttons.
In any way, going further, you will need to also control if the user has unchecked the checkbox.
Given a list of checkboxes as:
<input type='checkbox' >A
<input type='checkbox' >B
<input type='checkbox' >C
<input type='checkbox' >D
The script part could work like this:
<script>
var checked = false; //will save current state of checkboxes
$('input:checkbox').click(function(){
//if one was checked and then unchecked will enable all and return
if(checked)
{
$('input:checkbox').each(function(){
$(this).prop('disabled', false);
});
checked = false;
return;
}
//if none was checked before, disable the rest
$('input:checkbox').each(function(){
if(!$(this).is(':checked')){
$(this).prop('disabled', true);
}
else
checked = true;
});
});
</script>
FIDDLE
I have created a JsFiddle for you:
http://jsfiddle.net/jK4NE/
In short, I added a class myCheckBox on each checkBox and added the below jQuery code on Click:
$('.myCheckBox').click(function(){
var currentId = $(this).attr('id');
$('.myCheckBox').each(function(){
if($(this).attr('id') != currentId){
$(this).attr("checked", false);
}
});
});
If you have checkBoxes under a particular ID then you can target the same by using
#YourID input:checkbox
Example:
$('#YourID input:checkbox').click(function(){
var currentId = $(this).attr('id');
$('#YourID input:checkbox').each(function(){
if($(this).attr('id') != currentId){
$(this).attr("checked", false);
}
});
});
try this
HTML:
<ul>
<li><input type="checkbox" name="gender" value="male">Male</li>
<li><input type="checkbox" name="gender" value="female">Female</li>
</ul>
jQuery Code
$('input').change(function(){
if( $(this).prop('checked') ){
$(this).parent().parent().find('input').prop('disabled', true);
$(this).prop('disabled', false);
}
});
Demo
This is how you do
$(document).ready(function () {
var checked = false;
$('#<%=lstExposureValue.ClientID%> input:checkbox').click(function () {
var currentIdone = 'Unknown';
var currentId = $(this).next().html();
if (currentId == currentIdone) {
if (checked) {
$("#<%=lstExposureValue.ClientID%> input").removeAttr('disabled');
checked = false;
return;
}
else {
$("#<%=lstExposureValue.ClientID%> input").attr('checked', false);
$(this).attr('checked', true);
$('#<%=lstExposureValue.ClientID%> input:not(:checked)').attr('disabled', 'disabled');
checked = true;
}
}
});
});

cannot check/uncheck checkbox in javascript/jquery

I have a checkbox which will toggle some other check boxes on a html form:
<input type="checkbox" name="selector" onclick="toggle_all(this);"/>
<script language="javascript">
function toggle_all(source) {
var checkboxes = $(":input[name^='form[r']");
if($(source).is(':checked')) {
checkboxes.attr('checked', 'checked');
} else {
checkboxes.removeAttr('checked');
}
alert('done');
}
</script>
First time I click the "selector" check box, all check boxes with names starting "form[r" will be checked. Then when "selector" check box is unchecked, all others are unchecked as well. Since then checking/unchecking "selector" checkbox doesn't affect other checkboxes. The code is running because alert('done') shows up. What's wrong here?
I would suggest an improvement. Change HTML, add some class to all your checkboxes:
<input class="check" type="checkbox" name="form[r]">
And JS:
function toggle_all(source) {
$(".check").prop('checked', source.checked);
}
http://jsfiddle.net/tFv3G/
And the reason why is that searching elements by its attributes much slower than by class name. And less readable as well.
You need to escape the square bracket in selector
Change
var checkboxes = $(":input[name^='form[r']");
To
var checkboxes = $(":input[name^='form\[r']");
I'd recomment using this code to select/deselect all checkboxes:
$('input#select-all').change(function(){
var checked = $(this).prop('checked');
$(":input[name^='form[r']").prop('checked', checked);
});

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