Check if n number of checkboxs are not checked - javascript

I have the following HTML elements:
<input type="checkbox" id="dog_pop_123">
<input type="checkbox" id="cat_pop_123">
<input type="checkbox" id="parrot_pop_123">
I want to check that, if the three of the checkboxes are not checked, I need to return false. However, I need to take into account that the third checkbox might not exist.
Right now I have this:
var id = 123;
if ( !$('#dog_pop_'+id+':checked').length
&& !$('#cat_pop_'+id+':checked').length
&& !$('#parrot_pop_'+id+':checked').length ) {
return false;
}
However, if the last input doesn't exist, and the first two do exist and are checked, this would return false, and it should not.
How can I solve this?

I'd suggest grouping the checkboxes together within a common parent:
<fieldset id="group1">
<input type="checkbox" id="dog_pop_123">
<input type="checkbox" id="cat_pop_123">
<input type="checkbox" id="parrot_pop_123">
</fieldset>
And using the following:
return !($('#group1 input:checkbox').length == $('#group1 input:checkbox:not(":checked")').length);
Effectively if the number of checkboxes is equal to the number of un-checked checkboxes return false (using the ! operator), else return true.
References:
:checkbox selector.
:checked selector.
:not() selector.

if($('input[id$="pop_123"]').length != $('input[id$="pop_123"]:checked').length ) {
return false;
}
should do the trick unless you have many ids ending in pop_123. In that case, you can add the [type=checkbox] filter too.
Using $= in the selector means ends with. See documentation

Try the following code:
var id = 123,
checkboxes = $('#dog_pop_' + id + ', #cat_pop_' + id + ', #parrot_pop_' + id);
if(checkboxes.filter(function() {return this.checked !== true;}).length !== checkboxes.length) {
//Not all checkboxes are checked
}

Related

Checking between two radio buttons with javascript .prop('checked');

I have these two radio buttons and I am checking to see if one of them is checked with the below javascript. As I type this question I realize that my script only checks if a specific radio button is checked. How can I check to verify that one of the two are checked?
jQuery(".GenderM1").each(function() {
var isChecked = jQuery(this).prop('checked');
if (isChecked == false) {
e.preventDefault();
pass = "false";
alert("Please select gender.");
return false;
}
});
<td>
<input type="radio" name="persinfo_gender[0]" <?php if($row_c->persinfo_gender == "0") echo "checked";?> id="maleradio" class="GenderM1" value="0" required>M
<br>
<input type="radio" name="persinfo_gender[0]" <?php if($row_c->persinfo_gender == "1") echo "checked";?> id="female_redio" class="GenderM1" value="1" required>F
</td>
Your code
jQuery(".GenderM1").each(function() {
var isChecked = jQuery(this).prop('checked');
if (isChecked == false) {
e.preventDefault();
pass = "false";
alert("Please select gender.");
return false;
}
});
You're comparing a boolean variable against a boolean value, use it directly:
isChecked == false// Use !isChecked
^
You're using an undeclared e, probably you thin that .each receives an event.
e.preventDefault();
^
The main problem is your loop comparing each radiobutton.checked attribute, you need to check is at least one of then is checked to stop your loop.
This code snippet show how to check if a radiobutton was checked:
var isChecked = false;
jQuery(".GenderM1").each(function() {
isChecked = isChecked || jQuery(this).is(':checked');
if (isChecked)
return false;
});
if (!isChecked) {
var pass = "false";
alert("Please select gender.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="persinfo_gender[0]" class="GenderM1" value="0" required>M
<br>
<input type="radio" name="persinfo_gender[0]" checked class="GenderM1" value="1" required>F
See?, the alert is not being shown when a radiobutton is checked.
Now, the best approach to know whether a radiobutton group has at least one of them checked:
$('.GenderM1:checked').length
The line above returns how many radiobuttons are checked (1 or 0) because you only can select one of then. That selector works with checkboxes as well.
the method .prop() is available since jQuery 1.6, in previous versions you have to use the method .attr()
which version do you use?
Still I think that what you want to do is that if you have not selected a genre that shows an error and with the code you have, it will not work well. To do this you must do the following:
1- Mark one of them selected by default, that is, establish it as checked by default, this eliminates the possibility that the error of not marking it will be committed.
2- Modify the validation you perform, otherwise it will always return false because only one will be selected and you will go through the entire radiobuttons arrangement, so that when you reach the unselected radiobuttons it will return false.
if ($('input[class="GenderM1"]').is(':checked')) {
// do something;
} else {
//do another thing;
}

jQuery - serializeArray() is not getting the value of the checked checkbox

I have a checkbox in a form that acts as a flag.
In order to do it, I added a hidden input element so that if the checkbox is not checked, something will still be saved
<form action="">
...
<input type="hidden" name="foo" value="no" />
<input type="checkbox" name="foo" value="yes">
...
</form>
The problem I am having is that when I
check the checkbox
then run jQuery.serializeArray() on the form
the value set for the foo element is "no"
Object { name="foo", value="no"}
Shouldn't serializeArray() emulate browser behaviour? If so, shouldn't it return "yes" if checkbox is checked?
I am using jQuery v1.10.2
In a short word: No. The serializeArray method only returns the checkbox in the case it is checked. Thus, it will ignore it as long as it remains unchecked.
In case you checked it, though, it wiill return the value of your input directly.
Check out the demo at http://api.jquery.com/serializearray/ .
Using serializeArray on a form with multiple inputs of the same name returns more than one object for each element (if checked). This means that the following HTML will return the following object. So the data in question is there and is available. Because of this I'm assuming that you're attempting to either manipulate the data to be in 1 object or you're posting it to a server which is only taking into account the data from the first value with that key. You just need to make sure that any checkbox element takes precedence.
Returned Object:
[
{
name:"foo",
value:"no"
},
{
name:"foo2",
value:"no"
},
{
name:"foo2",
value:"yes"
}
]
HTML:
<form>
<input type="hidden" name="foo" value="no" />
<input type="checkbox" name="foo" value="yes" />
<input type="hidden" name="foo2" value="no" />
<input type="checkbox" name="foo2" value="yes" checked />
</form>
JS:
console.log($('form').serializeArray());
DEMO
Another way you can do this is get rid of the hidden fields and before you submit the form go through each unchecked checkbox and check if there is any data in the serializeArray with the same name. If not just add it in there as a off.
$('#submit').on('click', function(){
var arr = $('form').serializeArray(),
names = (function(){
var n = [],
l = arr.length - 1;
for(; l>=0; l--){
n.push(arr[l].name);
}
return n;
})();
$('input[type="checkbox"]:not(:checked)').each(function(){
if($.inArray(this.name, names) === -1){
arr.push({name: this.name, value: 'off'});
}
});
console.log(arr);
});
DEMO
Using the same name for multiple fields is problematic at best and there is no standardized way that front end systems, or back end systems, will handle it.
The only reason to use the same name is if you are trying to pass some kind of a default value, like you are in the case below, where you are doing a simple yes/no.
What you want, to emulate the browser, is serialize method, not the serializeArray.
I added the form to a page -- from my console:
JSON.stringify(f.serializeArray());
"[{"name":"foo","value":"no"}]"
NO checkmark
JSON.stringify(f.serialize());
""foo=no""
Checkmark
JSON.stringify(f.serialize());
""foo=yes&foo=no""
If your back end system gets confused and is picking up the wrong value, reverse the order of your checkmark and hidden element.
FACT: jQuery serializeArray() does not include unchecked checkboxes that probably we DO need them sent to server (no problem for radios though).
SOLUTION: create a new serialize:
//1. `sel` any collection of `form` and/or `input`, `select`, `textarea`
//2. we assign value `1` if not exists to radios and checkboxes
// so that the server will receive `1` instead of `on` when checked
//3. we assign empty value to unchecked checkboxes
function serialize(sel) {
var arr,
tmp,
i,
$nodes = $(sel);
// 1. collect form controls
$nodes = $nodes.map(function(ndx){
var $n = $(this);
if($n.is('form'))
return $n.find('input, select, textarea').get();
return this;
});
// 2. replace empty values of <input>s of type=["checkbox"|"radio"] with 1
// or, we end up with "on" when checked
$nodes.each(function(ndx, el){
if ((el.nodeName.toUpperCase() == 'INPUT') && ((el.type.toUpperCase() == 'CHECKBOX') || (el.type.toUpperCase() == 'RADIO'))){
if((el.value === undefined) || (el.value == ''))
el.value = 1;
}
});
// 3. produce array of objects: {name: "field attribute name", value: "actual field value"}
arr = $nodes.serializeArray();
tmp = [];
for(i = 0; i < arr.length; i++)
tmp.push(arr[i].name);
// 4. include unchecked checkboxes
$nodes.filter('input[type="checkbox"]:not(:checked)').each(function(){
if(tmp.indexOf(this.name) < 0){
arr.push({name: this.name, value: ''});
}
});
return arr;
}
The reason we assigned empty string to unchecked checkboxes is because a checked one will submit it's value to server which is set in html and can be a zero!!!
So, an empty value denotes a unchecked checkbox.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<form url="http://application.localdev/api/v1/register" method="post" id="formReg" accept-charset="utf-8">
<input type="email" placeholder="email" name="email"><br>
<input type="text" placeholder="firstname" name="firstname"><br>
<input type="text" placeholder="lastname" name="lastname"><br>
<input type="number" placeholder="zip_code" name="zip_code"><br>
<input type="checkbox" name="general" value="true"> general<br>
<input type="checkbox" name="marketing" value="true"> marketing<br>
<input type="checkbox" name="survey" value="true"> survey<br>
<button type="submit">save</button>
</form>
<script>
$(document).ready(function() {
$('#formReg').on('submit', function(e){
// validation code here
e.preventDefault();
var values = {};
$.each($('#formReg').serializeArray(), function(i, field) {
values[field.name] = field.value;
});
$('input[type="checkbox"]:not(:checked)').each(function(){
if($.inArray(this.name, values) === -1){
values[this.name] = $(this).prop('checked')
}
});
console.log(values)
});
});
</script>
serializeArray doesn't return unchecked checkbox. I try this instead of serializeArray:
$('input, select, textarea').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') +
'Value: ' + input.val());
}
);

check checkbox if another checkbox is checked

I want the checkbox with the value 2 to automatically get checked if the checkbox with the value 1 is checked. Both have the same id so I can't use getElementById.
html:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name">2
I tired:
var chk1 = $("input[type="checkbox"][value="1"]");
var chk2 = $("input[type="checkbox"][value="2"]");
if (chk1:checked)
chk2.checked = true;
You need to change your HTML and jQuery to this:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.on('change', function(){
chk2.prop('checked',this.checked);
});
id is unique, you should use class instead.
Your selector for chk1 and chk2 is wrong, concatenate it properly using ' like above.
Use change() function to detect when first checkbox checked or unchecked then change the checked state for second checkbox using prop().
Fiddle Demo
Id should be unique, so that set different ids to your elements, By the way you have to use .change() event to achieve what you want.
Try,
HTML:
<input type="checkbox" value="1" id="user_name1">1<br>
<input type="checkbox" value="2" id="user_name2">2
JS:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.change(function(){
chk2.prop('checked',this.checked);
});
You need to change the ID of one. It is not allowed by W3C standard (hence classes vs ID's). jQuery will only process the first ID, but most major browsers will treat ID's similar to classes since they know developers mess up.
Solution:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name_2">2
With this JS:
var chk1 = $('#user_name');
var chk2 = $('#user_name2');
//check the other box
chk1.on('click', function(){
if( chk1.is(':checked') ) {
chk2.attr('checked', true);
} else {
chk2.attr('checked', false);
}
});
For more information on why it's bad to use ID's see this: Why is it a bad thing to have multiple HTML elements with the same id attribute?
The error is probably coming here "input[type="checkbox"]
Here your checkbox is out of the quotes, so you query is looking for input[type=][value=1]
Change it to "input[type='checkbox'] (Use single quote inside double quote, though you don't need to quote checkbox)
http://api.jquery.com/checked-selector/
first create an input type checkbox:
<input type='checkbox' id='select_all'/>
$('#select_all').click(function(event) {
if(this.checked) {
$(':checkbox').each(function() {
this.checked = true;
});
}
});

JS / JQuery - Check All Checkboxes

I have a photo gallery. Underneath each photo is a checkbox, with the ID containing a prefix of 'checkbox_', followed by the photo ID.
<input type="checkbox" id="checkbox_<%=photoID%>" name="photos">
When I check a 'selectAll' checkbox, like this one:
<input type="checkbox" id="toggleAll" name="toggleAll" onclick="toggleAll()">
I want to check/uncheck all checkboxes that have the name 'photos', so I have this function that should do that... but it doesn't:
function toggleAll() {
if (document.getElementById('toggleAll').checked == true)
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,102,204,0.5)'}, 500);
$('.photoBlob').animate({backgroundColor: 'rgba(204,204,204,1)'}, 1500);
document.getElementByName('photos').checked = true;
}
else
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,0,0,0)'}, 1000);
document.getElementByName('photos').checked = false;
}
}
The rest of the function works okay, it animates the background colors of the containing DIV (#photoBlob) when the toggleALL() function is called. But, I really can't get all the checkboxes to check and I have tried so many different variations!
Can anybody see what I am doing wrong? The problem lies with these two lines:
document.getElementByName('photos').checked = true;
document.getElementByName('photos').checked = false;
Any suggestions gratefully received...
You can do like this,
don't use same name for several check boxes because the name shroud be unique. Instead of use the class.
<input type="checkbox" id="checkbox_<%=photoID%>" class="photos">
an the jquery,
$('#toggleAll').click(function(){
var checked =$(this).attr('checked');
$('.photos').attr('checked', checked);
}
$('#toggleAll').click(function(){
$(':checkbox[name="photos"]').prop('checked',this.checked);
});
Fiddle demo: http://jsfiddle.net/uNeX2/
I think you're missing an "s" in getElementByTagName. Try getElementsByTagName.
This might also work:
$("#toggleAll").click(function() {<br/>
$("input[name='photos']").attr("checked",!!$(this).attr("checked"));
});
well, since you said, you have multiple checkboxes with the name 'photos', selecting only one element by using the function getElementByName, can't be ur choice of game. Using jQuery simplifies the task your trying to do;
$("input[name=photos]").each(function(elem){
elem.checked=true;
}
or simpler;
$("input[name=photos]").attr('checked','checked');
its its js-only, youd need to select all input elements via getElementsByTagName and then filter out the ones that don't comply with having a name of 'photos'.. and then do your task.
Here is simple example using jQuery:
html
<input type="checkbox" id="all" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
js
$('#all').click(function() {
if ($(this).attr('checked') == undefined) {
$('input[name=photo]').removeAttr('checked');
}
else {
$('input[name=photo]').attr('checked', 'checked');
}
});
Code: http://jsfiddle.net/b8Y9t/3/
I would use:
$('.photos:checkbox').attr('checked','checked');
There is no function called getElementByName. Did you have a javascript-error? I think it should be getElementsByName. This returns a list with elements. That means you have to loop trough it to check all checkboxes.
BTW I think it is not correct to use a name called 'photos' for a checkbox, since a checkbox is a single object and does not display a photo itself. I would name it 'photoCheckbox' or 'cbPhoto' to clearify it is a checkbox.
var checkboxList = getElementsByName('photoCheckbox'); // returns list with checkboxes with name 'photoCheckbox'
if (checkboxList)
{
for (var i = 0; i < checkboxList.length; i++)
{
var checkbox = checkboxList[i];
checkbox.checked = false;
}
}
Thats how the getElementsByName function works. So if you would evaluate this method, you would say this is unnecessary since you are already using jQuery? I would simplify the code of the checkbox:
<input type="checkbox" onclick="toggleAll(this)" />
The new toggleAll function looks like this:
function toggleAll(checkbox)
{
if (checkbox.checked)
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,102,204,0.5)'}, 500);
$('.photoBlob').animate({backgroundColor: 'rgba(204,204,204,1)'}, 1500); // btw why 2 animations on the same elements..?
$('input[name="photos"]').prop("checked", true);
}
else
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,0,0,0)'}, 1000);
$('input[name="photos"]').prop("checked", false);
}
}
// jquery check all or uncheck all
$('.checkall').click(function(){
var status = 'false';
status = $('.checkall').is(":checked");
//alert ('status is ' + status); // you should see true or false
$('.metacheckbox').each( function() {
$(this).attr('checked', status);
});
});
<input class="checkall" type="checkbox" />Check/UnCheck All
<input class="metacheckbox" type="checkbox" id='checkboxone' name="checkboxone" value="Y" />
<input class="metacheckbox" type="checkbox" id='checkboxtwo' name="checkboxtwo" value="Y" />
<input class="metacheckbox" type="checkbox" id='checkboxthree' name="checkboxthree" value="Y" />
this worked for me.

Check if checkbox is checked with jQuery

How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array?
I am using the following code, but it always returns the count of checked checkboxes regardless of id.
function isCheckedById(id) {
alert(id);
var checked = $("input[#id=" + id + "]:checked").length;
alert(checked);
if (checked == 0) {
return false;
} else {
return true;
}
}
$('#' + id).is(":checked")
That gets if the checkbox is checked.
For an array of checkboxes with the same name you can get the list of checked ones by:
var $boxes = $('input[name=thename]:checked');
Then to loop through them and see what's checked you can do:
$boxes.each(function(){
// Do stuff here with this
});
To find how many are checked you can do:
$boxes.length;
IDs must be unique in your document, meaning that you shouldn't do this:
<input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />
Instead, drop the ID, and then select them by name, or by a containing element:
<fieldset id="checkArray">
<input type="checkbox" name="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>
And now the jQuery:
var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector
// or, without the container:
var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;
$('#checkbox').is(':checked');
The above code returns true if the checkbox is checked or false if not.
All following methods are useful:
$('#checkbox').is(":checked")
$('#checkbox').prop('checked')
$('#checkbox')[0].checked
$('#checkbox').get(0).checked
It is recommended that DOMelement or inline "this.checked" should be avoided instead jQuery on method should be used event listener.
jQuery code to check whether the checkbox is checked or not:
if($('input[name="checkBoxName"]').is(':checked'))
{
// checked
}else
{
// unchecked
}
Alternatively:
if($('input[name="checkBoxName"]:checked'))
{
// checked
}else{
// unchecked
}
The most important concept to remember about the checked attribute is
that it does not correspond to the checked property. The attribute
actually corresponds to the defaultChecked property and should be used
only to set the initial value of the checkbox. The checked attribute
value does not change with the state of the checkbox, while the
checked property does. Therefore, the cross-browser-compatible way to
determine if a checkbox is checked is to use the property
All below methods are possible
elem.checked
$(elem).prop("checked")
$(elem).is(":checked")
This is also an idea I use frequently:
var active = $('#modal-check-visible').prop("checked") ? 1 : 0 ;
If cheked, it'll return 1; otherwise it'll return 0.
You can use this code,
if($("#checkboxId").is(':checked')){
// Code in the case checkbox is checked.
} else {
// Code in the case checkbox is NOT checked.
}
As per the jQuery documentation there are following ways to check if a checkbox is checked or not. Lets consider a checkbox for example (Check Working jsfiddle with all examples)
<input type="checkbox" name="mycheckbox" id="mycheckbox" />
<br><br>
<input type="button" id="test-with-checked" value="Test with checked" />
<input type="button" id="test-with-is" value="Test with is" />
<input type="button" id="test-with-prop" value="Test with prop" />
Example 1 - With checked
$("#test-with-checked").on("click", function(){
if(mycheckbox.checked) {
alert("Checkbox is checked.");
} else {
alert("Checkbox is unchecked.");
}
});
Example 2 - With jQuery is, NOTE - :checked
var check;
$("#test-with-is").on("click", function(){
check = $("#mycheckbox").is(":checked");
if(check) {
alert("Checkbox is checked.");
} else {
alert("Checkbox is unchecked.");
}
});
Example 3 - With jQuery prop
var check;
$("#test-with-prop").on("click", function(){
check = $("#mycheckbox").prop("checked");
if(check) {
alert("Checkbox is checked.");
} else {
alert("Checkbox is unchecked.");
}
});
Check Working jsfiddle
I know the OP want jquery but in my case pure JS was the answer so if anyone like me is here and do not have jquery or do not want to use it - here is the JS answer:
document.getElementById("myCheck").checked
It returns true if the input with ID myCheck is checked and false if it is not checked.
Simple as that.
You can try this:
<script>
function checkAllCheckBox(value)
{
if($('#select_all_').is(':checked')){
$(".check_").attr ( "checked" ,"checked" );
}
else
{
$(".check_").removeAttr('checked');
}
}
</script>
<input type="checkbox" name="chkbox" id="select_all_" value="1" />
<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />
<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />
You can use any of the following recommended codes by jquery.
if ( elem.checked ) {};
if ( $( elem ).prop( "checked" ) ) {};
if ( $( elem ).is( ":checked" ) ) {};
You can do it simply like;
Working Fiddle
HTML
<input id="checkbox" type="checkbox" />
jQuery
$(document).ready(function () {
var ckbox = $('#checkbox');
$('input').on('click',function () {
if (ckbox.is(':checked')) {
alert('You have Checked it');
} else {
alert('You Un-Checked it');
}
});
});
or even simpler;
$("#checkbox").attr("checked") ? alert("Checked") : alert("Unchecked");
If the checkbox is checked it will return true otherwise undefined
$(document).on('click','#checkBoxId',function(){
var isChecked = $(this).is(':checked');
console.log(isChecked);
});
This code above works also on bootstrap modal. isChecked is true or flase ;
Simple Demo for checking and setting a check box.
jsfiddle!
$('.attr-value-name').click(function() {
if($(this).parent().find('input[type="checkbox"]').is(':checked'))
{
$(this).parent().find('input[type="checkbox"]').prop('checked', false);
}
else
{
$(this).parent().find('input[type="checkbox"]').prop('checked', true);
}
});
Just to say in my example the situation was a dialog box that then verified the check box before closing dialog. None of above and How to check whether a checkbox is checked in jQuery? and jQuery if checkbox is checked did not appear to work either.
In the end
<input class="cb" id="rd" type="checkbox">
<input class="cb" id="fd" type="checkbox">
var fd=$('.cb#fd').is(':checked');
var rd= $('.cb#rd').is(':checked');
This worked so calling the class then the ID. rather than just the ID. It may be due to the nested DOM elements on this page causing the issue. The workaround was above.
For checkbox with an id
<input id="id_input_checkbox13" type="checkbox"></input>
you can simply do
$("#id_input_checkbox13").prop('checked')
you will get true or false as return value for above syntax. You can use it in if clause as normal boolean expression.
Actually, according to jsperf.com, The DOM operations are fastest, then $().prop() followed by $().is()!!
Here are the syntaxes :
var checkbox = $('#'+id);
/* OR var checkbox = $("input[name=checkbox1]"); whichever is best */
/* The DOM way - The fastest */
if(checkbox[0].checked == true)
alert('Checkbox is checked!!');
/* Using jQuery .prop() - The second fastest */
if(checkbox.prop('checked') == true)
alert('Checkbox is checked!!');
/* Using jQuery .is() - The slowest in the lot */
if(checkbox.is(':checked') == true)
alert('Checkbox is checked!!');
I personally prefer .prop(). Unlike .is(), It can also be used to set the value.
Something like this can help
togglecheckBoxs = function( objCheckBox ) {
var boolAllChecked = true;
if( false == objCheckBox.checked ) {
$('#checkAll').prop( 'checked',false );
} else {
$( 'input[id^="someIds_"]' ).each( function( chkboxIndex, chkbox ) {
if( false == chkbox.checked ) {
$('#checkAll').prop( 'checked',false );
boolAllChecked = false;
}
});
if( true == boolAllChecked ) {
$('#checkAll').prop( 'checked',true );
}
}
}
Try this...
$(function(){
$('body').on('click','.checkbox',function(e){
if($(this).is(':checked')){
console.log('Checked')
} else {
console.log('Unchecked')
}
})
})
Toggle checkbox checked
$("#checkall").click(function(){
$("input:checkbox").prop( 'checked',$(this).is(":checked") );
})
Using this code you can check at least one checkbox is selected or not in different checkbox groups or from multiple checkboxes.
Using this you can not require to remove IDs or dynamic IDs. This code work with the same IDs.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox21" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox22" value=ck2 /> ck2<br />
<label class="control-label col-sm-4">Check Box 3</label>
<input type="checkbox" name="checkbox3" id="checkbox31" value=ck3 /> ck3<br />
<input type="checkbox" name="checkbox3" id="checkbox32" value=ck4 /> ck4<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
if (!$('input[name=checkbox3]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 3 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
Since it's mid 2019 and jQuery sometimes takes a backseat to things like VueJS, React etc. Here's a pure vanilla Javascript onload listener option:
<script>
// Replace 'admincheckbox' both variable and ID with whatever suits.
window.onload = function() {
const admincheckbox = document.getElementById("admincheckbox");
admincheckbox.addEventListener('click', function() {
if(admincheckbox.checked){
alert('Checked');
} else {
alert('Unchecked');
}
});
}
</script>
Your question is not clear: you want to give "checkbox array id" at input and get true/false at output - in this way you will not know which checkbox was checked (as your function name suggest). So below there is my proposition of body of your isCheckedById which on input take checkbox id and on output return true/false (it's very simple but your ID should not be keyword),
this[id].checked
function isCheckedById(id) {
return this[id].checked;
}
// TEST
function check() {
console.clear()
console.log('1',isCheckedById("myCheckbox1"));
console.log('2',isCheckedById("myCheckbox2"));
console.log('3',isCheckedById("myCheckbox3"));
}
<label><input id="myCheckbox1" type="checkbox">check 1</label>
<label><input id="myCheckbox2" type="checkbox">check 2</label>
<label><input id="myCheckbox3" type="checkbox">check 3</label>
<!-- label around inputs makes text clickable -->
<br>
<button onclick="check()">show checked</button>
You can try either any of the ways preferred, as in jQuery or JavaScript.
Get the value as below and assign to the variable then you if-else statements as per your requirement.
var getVal=$('#checkbox_id').is(":checked"); // jQuery
var getVal=document.getElementById("checkbox_id").checked //JavaScript
if (getVal==true) {
// perform task
} else {
// perform task
}
use code below
<script>
$(document).ready(function () {
$("[id$='chkSendMail']").attr("onchange", "ShowMailSection()");
}
function ShowMailSection() {
if ($("[id$='chkSendMail'][type='checkbox']:checked").length >0){
$("[id$='SecEmail']").removeClass("Hide");
}
</script>

Categories