Related
I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.
For example, if the age checkbox is checked, then I need to show a textbox to enter age, else hide the textbox.
But the following code returns false by default:
if ($('#isAgeSelected').attr('checked')) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">
Age is selected
</div>
How do I successfully query the checked property?
How do I successfully query the checked property?
The checked property of a checkbox DOM element will give you the checked state of the element.
Given your existing code, you could therefore do this:
if(document.getElementById('isAgeSelected').checked) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
However, there's a much prettier way to do this, using toggle:
$('#isAgeSelected').click(function() {
$("#txtAge").toggle(this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>
Use jQuery's is() function:
if($("#isAgeSelected").is(':checked'))
$("#txtAge").show(); // checked
else
$("#txtAge").hide(); // unchecked
Using jQuery > 1.6
<input type="checkbox" value="1" name="checkMeOut" id="checkMeOut" checked="checked" />
// traditional attr
$('#checkMeOut').attr('checked'); // "checked"
// new property method
$('#checkMeOut').prop('checked'); // true
Using the new property method:
if($('#checkMeOut').prop('checked')) {
// something when checked
} else {
// something else when not
}
jQuery 1.6+
$('#isAgeSelected').prop('checked')
jQuery 1.5 and below
$('#isAgeSelected').attr('checked')
Any version of jQuery
// Assuming an event handler on a checkbox
if (this.checked)
All credit goes to Xian.
I am using this and this is working absolutely fine:
$("#checkkBoxId").attr("checked") ? alert("Checked") : alert("Unchecked");
Note: If the checkbox is checked it will return true otherwise undefined, so better check for the "TRUE" value.
Use:
<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned
$("#planned_checked").change(function() {
if($(this).prop('checked')) {
alert("Checked Box Selected");
} else {
alert("Checked Box deselect");
}
});
$("#planned_checked").change(function() {
if($(this).prop('checked')) {
alert("Checked Box Selected");
} else {
alert("Checked Box deselect");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned
Since jQuery 1.6, the behavior of jQuery.attr() has changed and users are encouraged not to use it to retrieve an element's checked state. Instead, you should use jQuery.prop():
$("#txtAge").toggle(
$("#isAgeSelected").prop("checked") // For checked attribute it returns true/false;
// Return value changes with checkbox state
);
Two other possibilities are:
$("#txtAge").get(0).checked
$("#txtAge").is(":checked")
This worked for me:
$get("isAgeSelected ").checked == true
Where isAgeSelected is the id of the control.
Also, #karim79's answer works fine. I am not sure what I missed at the time I tested it.
Note, this is answer uses Microsoft Ajax, not jQuery
If you are using an updated version of jquery, you must go for .prop method to resolve your issue:
$('#isAgeSelected').prop('checked') will return true if checked and false if unchecked. I confirmed it and I came across this issue earlier. $('#isAgeSelected').attr('checked') and $('#isAgeSelected').is('checked') is returning undefined which is not a worthy answer for the situation. So do as given below.
if($('#isAgeSelected').prop('checked')) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
Use:
<input type="checkbox" id="abc" value="UDB">UDB
<input type="checkbox" id="abc" value="Prasad">Prasad
$('input#abc').click(function(){
if($(this).is(':checked'))
{
var checkedOne=$(this).val()
alert(checkedOne);
// Do some other action
}
})
This can help if you want that the required action has to be done only when you check the box not at the time you remove the check.
You can try the change event of checkbox to track the :checked state change.
$("#isAgeSelected").on('change', function() {
if ($("#isAgeSelected").is(':checked'))
alert("checked");
else {
alert("unchecked");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected" />
<div id="txtAge" style="display:none">
Age is selected
</div>
Using the Click event handler for the checkbox property is unreliable, as the checked property can change during the execution of the event handler itself!
Ideally, you'd want to put your code into a change event handler such as it is fired every time the value of the check box is changed (independent of how it's done so).
$('#isAgeSelected').bind('change', function () {
if ($(this).is(':checked'))
$("#txtAge").show();
else
$("#txtAge").hide();
});
I ran in to the exact same issue. I have an ASP.NET checkbox
<asp:CheckBox ID="chkBox1" CssClass='cssChkBox1' runat="server" />
In the jQuery code I used the following selector to check if the checkbox was checked or not, and it seems to work like a charm.
if ($("'.cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }
I'm sure you can also use the ID instead of the CssClass,
if ($("'#cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }
I hope this helps you.
I believe you could do this:
if ($('#isAgeSelected :checked').size() > 0)
{
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
I decided to post an answer on how to do that exact same thing without jQuery. Just because I'm a rebel.
var ageCheckbox = document.getElementById('isAgeSelected');
var ageInput = document.getElementById('txtAge');
// Just because of IE <333
ageCheckbox.onchange = function() {
// Check if the checkbox is checked, and show/hide the text field.
ageInput.hidden = this.checked ? false : true;
};
First you get both elements by their ID. Then you assign the checkboxe's onchange event a function that checks whether the checkbox got checked and sets the hidden property of the age text field appropriately. In that example using the ternary operator.
Here is a fiddle for you to test it.
Addendum
If cross-browser compatibility is an issue then I propose to set the CSS display property to none and inline.
elem.style.display = this.checked ? 'inline' : 'none';
Slower but cross-browser compatible.
This code will help you
$('#isAgeSelected').click(function(){
console.log(this.checked);
if(this.checked == true) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
});
This works for me:
/* isAgeSelected being id for checkbox */
$("#isAgeSelected").click(function(){
$(this).is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
});
There are many ways to check if a checkbox is checked or not:
Way to check using jQuery
if (elem.checked)
if ($(elem).prop("checked"))
if ($(elem).is(":checked"))
if ($(elem).attr('checked'))
Check example or also document:
http://api.jquery.com/attr/
http://api.jquery.com/prop/
This is some different method to do the same thing:
$(document).ready(function (){
$('#isAgeSelected').click(function() {
// $("#txtAge").toggle(this.checked);
// Using a pure CSS selector
if ($(this.checked)) {
alert('on check 1');
};
// Using jQuery's is() method
if ($(this).is(':checked')) {
alert('on checked 2');
};
// // Using jQuery's filter() method
if ($(this).filter(':checked')) {
alert('on checked 3');
};
});
});
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>
Use this:
if ($('input[name="salary_in.Basic"]:checked').length > 0)
The length is greater than zero if the checkbox is checked.
My way of doing this is:
if ( $("#checkbox:checked").length ) {
alert("checkbox is checked");
} else {
alert("checkbox is not checked");
}
$(selector).attr('checked') !== undefined
This returns true if the input is checked and false if it is not.
You can use:
if(document.getElementById('isAgeSelected').checked)
$("#txtAge").show();
else
$("#txtAge").hide();
if($("#isAgeSelected").is(':checked'))
$("#txtAge").show();
else
$("#txtAge").hide();
Both of them should work.
$(document).ready(function() {
$('#agecheckbox').click(function() {
if($(this).is(":checked"))
{
$('#agetextbox').show();
} else {
$('#agetextbox').hide();
}
});
});
1) If your HTML markup is:
<input type="checkbox" />
attr used:
$(element).attr("checked"); // Will give you undefined as initial value of checkbox is not set
If prop is used:
$(element).prop("checked"); // Will give you false whether or not initial value is set
2) If your HTML markup is:
<input type="checkbox" checked="checked" />// May be like this also checked="true"
attr used:
$(element).attr("checked") // Will return checked whether it is checked="true"
Prop used:
$(element).prop("checked") // Will return true whether checked="checked"
This example is for button.
Try the following:
<input type="button" class="check" id="checkall" value="Check All" /> <input type="button" id="remove" value="Delete" /> <br/>
<input type="checkbox" class="cb-element" value="1" /> Checkbox 1 <br/>
<input type="checkbox" class="cb-element" value="2" /> Checkbox 2 <br/>
<input type="checkbox" class="cb-element" value="3" /> Checkbox 3 <br/>
$('#remove').attr('disabled', 'disabled');
$(document).ready(function() {
$('.cb-element').click(function() {
if($(this).prop('checked'))
{
$('#remove').attr('disabled', false);
}
else
{
$('#remove').attr('disabled', true);
}
});
$('.check:button').click(function()
{
var checked = !$(this).data('checked');
$('input:checkbox').prop('checked', checked);
$(this).data('checked', checked);
if(checked == true)
{
$(this).val('Uncheck All');
$('#remove').attr('disabled', false);
}
else if(checked == false)
{
$(this).val('Check All');
$('#remove').attr('disabled', true);
}
});
});
The top answer didn't do it for me. This did though:
<script type="text/javascript">
$(document).ready(function(){
$("#li_13").click(function(){
if($("#agree").attr('checked')){
$("#saveForm").fadeIn();
}
else
{
$("#saveForm").fadeOut();
}
});
});
</script>
Basically when the element #li_13 is clicked, it checks if the element # agree (which is the checkbox) is checked by using the .attr('checked') function. If it is then fadeIn the #saveForm element, and if not fadeOut the saveForm element.
To act on a checkbox being checked or unchecked on click.
$('#customCheck1').click(function() {
if (this.checked) {
console.log('checked');
} else {
console.log('un-checked');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="customCheck1">
EDIT: Not a nice programming expression if (boolean == true) though .checked property might return other type variables as well..
It is better to use .prop("checked") instead. It returns true and false only.
I am using this:
<input type="checkbox" id="isAgeSelected" value="1" /> <br/>
<input type="textbox" id="txtAge" />
$("#isAgeSelected").is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
Though you have proposed a JavaScript solution for your problem (displaying a textbox when a checkbox is checked), this problem could be solved just by css. With this approach, your form works for users who have disabled JavaScript.
Assuming that you have the following HTML:
<label for="show_textbox">Show Textbox</label>
<input id="show_textbox" type="checkbox" />
<input type="text" />
You can use the following CSS to achieve the desired functionality:
#show_textbox:not(:checked) + input[type=text] {display:none;}
For other scenarios, you may think of appropriate CSS selectors.
Here is a Fiddle to demonstrate this approach.
I have a checkbox on a form which works fine. When the form s clicked I am trying to change the value to 1, when not clicked the value should be zero. I am filling the field dynamically using JavaScript. The problem is, when I log it in console I get an empty value..
Checkbox field
function checkMark() {
var checkBox = document.getElementById("spouse");
if (checkBox.checked == true){
checkBox.value = '1';
} else {
checkBox.value = 'O';
}
}
var spouse = $('#spouse').val();
console.log(spouse);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="spouse" value="" class="spouse" onclick="checkMark()">
The reason of your issue is that you're logging just when the page is initially loaded. You have to log the result every time you change the checkbox value.
Also, you can use ternary operator in order to simplify the solution.
function checkMark() {
var checkBox = document.getElementById("spouse");
checkBox.value = checkBox.checked ? '1' : '0';
log();
}
function log(){
var spouse = $('#spouse').val();
console.log(spouse);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="spouse" value="" class="spouse" onclick="checkMark()">
Try calling your function over onChange instead of onClick
I want to save a checkbox with localstorage. So that when i have checked the box and I close the browser and i re-open it, it will still be checked. right now if i click on the checkbox and i press the save button it doesn't save the checkbox.
how can i achieve this?
this is my code:
<script>
function save(){
var checkbox = document.getElementById('checkbox1zaal1');
if(document.getElementById('checkbox1zaal1').checked) {
localStorage.setItem('checkbox1zaal1', true);
}
}
function load(){
var checked = localStorage.getItem('checkbox1zaal1');
if (checked == true) {
document.getElementById("checkbox1zaal1").setAttribute('checked','checked');
}
}
function wis(){
location.reload();
localStorage.clear()
}
</script>
<body onload="load()">
<input type="button" id="ReserveerButton1" value="save" onclick="save()"/>
<input type="button" id="Wisbutton1" value="delete" onclick="wis()"/>
<input type="checkbox" id="checkbox1zaal1">1e film van de dag</input>
</body>
thanks for any advice!
1). Because boolean true is not equal to string "true". So comparison checked == true is always false, and checkbox never gets checked.
Instead try this:
var checked = JSON.parse(localStorage.getItem('checkbox1zaal1'));
if (checked == true) {
document.getElementById("checkbox1zaal1").checked = true;
}
And remember whatever you store in localStorage is always a string, and only a string. That's why when you save something more complex then primitive value (for example some object) make sure to use JSON.stringify on it first.
When you retrieve the value from localStorage you should convert it back to it's corresponding javascript type.
In general load function can also be improved:
function load(){
var checked = JSON.parse(localStorage.getItem('checkbox1zaal1'));
document.getElementById("checkbox1zaal1").checked = checked;
}
2). Another problem will come up once you try to uncheck checkbox. You are not handling it currently, so change save function to this one:
function save(){
var checkbox = document.getElementById('checkbox1zaal1');
localStorage.setItem('checkbox1zaal1', checkbox.checked);
}
Demo: http://jsfiddle.net/Lwxoeyyp/1/
The problem is that you are storing value as "true" in localStorage which is a string format, Now at time of loading the page value is retrieved as string and you are comparing that String "true" with boolean true. This will return false. One small change as
if (checked == "true")
now this should work.
You can also retrieve the status of your checkbox this way:
var selCheck = document.getElementById("checkOne");
selCheck.checked = (localStorage.getItem("34_chkOne")=="true");
Obviously,
"checkOne" is the id of the checkbox.
"34_chkOne" is the name of the local storage variable.
To store the value, you simply use
var selCheck = document.getElementById("checkOne");
localStorage.setItem("34_chkOne", selCheck.checked);
and, as said above, a variable of type string will be stored.
am using this jquery code and is working with me better
$(function() {
var sound_t_s_data = localStorage.getItem("sound_t_s");
if (sound_t_s_data == "yes") {
$("#sound_t").prop('checked', true);
}
else if(sound_t_s_data == "no"){
$("#sound_t").prop('checked', false);
}
});
$("#sound_t").click(function() {
if ($(this).is(":checked")) {
localStorage.setItem("sound_t_s", "yes");
} else {
localStorage.setItem("sound_t_s", "no");
}
});
And if you want to us it in function use like this
//Play Audio
const s_a = new Audio("audio/s_a.mp3");
$( "#s_r" ).click(function() {
if ($('#sound_t').is(':checked')) {
s_a.play()
}
});
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.
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>