So I'm trying to disable a text field if a checkbox isn't selected however its not working as it should.
Example: http://jsfiddle.net/GV7U9/
<input type="checkbox" id="check" checked /><br />
#<input type="text" size="8" maxlength="6" id="colour" placeholder="ffffff" />
<script>
$('#check').change(function(){
if( $('#check:checked') ){
$('#colour').removeAttr('disabled');
} else {
$('#colour').attr('disabled','');
}
});
</script>
That is a short example of what I'm trying to do but it doesn't want to work. There are no errors in the console.
Could someone please explain why this isn't working?
Use .prop() also use the checked state to set the value
$('#check').change(function () {
$('#colour').prop('disabled', !this.checked);
});
Demo: Fiddle
try $('#check').is(':checked')
here's Fiddle
Use length to find if element is checked otherwise your condition will be true always. When the length is greater then 0 condition will be true and false otherwise.
if( $('#check:checked').length ){
$('#colour').removeAttr('disabled');
} else {
$('#colour').attr('disabled','');
}
You can use checked property directly without condtion.
$('#check').change(function () {
$('#colour').prop('disabled', !this.checked);
});
Try this:
$('#check').change(function(){
if($('#check').is(':checked')){
$('#colour').removeAttr('disabled');
} else {
$('#colour').attr('disabled','');
}
}).change();
In order to make your jsFiddle working, you need to:
1) Include jQuery library
2) Use is(':checked') to check whether checkbox is checked or not.
3) Trigger change() event on page load to catch the default checked status.
Fiddle Demo
use this.checked
$('#check').change(function(){
if(this.checked){
$('#colour').removeAttr('disabled');
} else {
$('#colour').attr('disabled',true);
}
});
FIDDLE
Here you go:
http://jsfiddle.net/4dwkG/
<input type="checkbox" id="check" checked /><br />
#<input type="text" size="8" maxlength="6" id="colour" placeholder="ffffff" />
<script>
$('#check').change(function(){
if( $('#check').is(":checked") ){
$('#colour').removeAttr('disabled');
} else {
$('#colour').attr('disabled','');
}
});
</script>
check this code..using this.checked
$('#check').change(function(){
if(this.checked)
$('#colour').removeAttr('disabled');
else
$('#colour').attr('disabled','disabled');
});
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 upgrade my jQuery library to 1.9.1 and have this code:
if (
!($("#Days_Sat").attr("checked"))
&& !($("#Days_Sun").attr("checked"))
&& !($("#Days_Mon").attr("checked"))
&& !($("#Days_Tu").attr("checked"))
&& !($("#Days_We").attr("checked"))
&& !($("#Days_Tr").attr("checked"))
&& !($("#Days_Fr").attr("checked"))) {
alert("pleas select day");
}
but even i select day checkbox the alert shown!
You can use is(':checked') to know the checkbox state, this will return true if checkbox is checked otherwise false. see below code
if (!($("#Days_Sat").is(':checked'))
&& !($("#Days_Sun").is(':checked'))
&& !($("#Days_Mon").is(':checked'))
&& !($("#Days_Tu").is(':checked'))
&& !($("#Days_We").is(':checked'))
&& !($("#Days_Tr").is(':checked'))
&& !($("#Days_Fr").is(':checked')))
{
alert("pleas select day");
}
If you have all your concerned checkbox id starting with Days then you can use jQuery start with selector to get all checkbox with id starting from 'Days_' and get the length of object to find if none of them is selected. see below code
var checked = $('input[id^="Days_"]:checked').length;
if(checked==0)
alert("pleas select day");
Use jQuery is method instead of attr.
jQuery API link.
Demo
Try
$('##Days_Sun').is(':checked');
You can use .is() method with :checked selector. like this:
$("#Days_Fr").is(":checked")
To make your code easiers to read i would go for:
if ( $('#Days_Sat, #Days_Sun, #Days_Mon, #Days_Tu, #Days_We, #Days_Tr, #Days_Fr').filter(':checked').length != 1 )
{
}
Other than that: like the other people already answered: .is(':checked') is your solution here.
Check like this
if(!$("[id^='Days_']").is(':checked')){
alert("pleas select day");
}
I would check if there is any ID starting with "Days_" that is checked. If not (!) the if clause will be thruthy.
if (!$("[id^='Days_']:checked").length) alert("pleas select day");
$('button').click(function(){
if (!$("[id^='Days_']:checked").length) alert('please choose a day...');
else alert('cool...');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="checkbox" id="Days_Sat" />
<input type="checkbox" id="Days_Sun" />
<input type="checkbox" id="Days_Mon" />
<input type="checkbox" id="Days_Tu" />
<input type="checkbox" id="Days_We" />
<input type="checkbox" id="Days_Tr" />
<input type="checkbox" id="Days_Fr" />
<button type="button">Test</button>
Look at the jsfiddle here JsFiddle
$(function(){
$('#check').click(function(){
if($("[id^='days_']:checked").length !=7 ){
alert("Please select a day");}
else{alert("works fine");}
});
});
This will popup the alert if any checkboxe is not clicked.
if you want that atleast one should be selected you can do
if($("[id^='days_']:checked").length !=0 )
$('#your_id').is(':checked') gives you either check box is checked or not.
It returns true if it is checked or false when not checked
if($('#Days_Sat').is(':checked'))
{
do something...
}
and you full code
if(!$('#Days_Sat').is(':checked')&&!$('#Days_Sun').is(':checked')&&!$('#Days_Mo').is(':checked')&&!$('#Days_Tu').is(':checked')&&!$('#Days_Th').is(':checked')&&!$('#Days_Fr').is(':checked'))
{
alert("pleas select day");
}
I've got this problem that I can't solve. Partly because I can't explain it with the right terms. I'm new to this so sorry for this clumsy question.
Below you can see an overview of my goal.
I'm running this code in Magento
<input type="checkbox" style="margin-left:24px" class="mydelete" name="checkAll" onclick='checkedAll(testCheck);' />
Added an id attribute to the element.
<input type="checkbox" style="margin-left:24px" class="mydelete" name="checkAll" id="checkAll"onclick='checkedAll();' />
Javascript
function checkedAll(){
if (document.getElementById('checkAll').checked) {
alert("checked");
} else {
alert("You didn't check it! Let me check it for you.")
}
}
DEMO
If you are flexible with using jQuery, you can easily do something like -
$("input:checkbox").is(":checked")
which will return a boolean value based on whether that input box is checked or not.
You can do this using below code.
var checkprop = document.getElementsByName("checkAll").checked;
alert(checkprop);
EDIT
function checkedAll()
{
var theform = document.theform;
if(theform.checkAll.checked )
{
alert("checkAll Checked");
} else {
alert("Nothing Selected");
}
}
<form name="theform">
<input type="checkbox" style="margin-left:24px" class="mydelete" name="checkAll" onclick='checkedAll();' />
</form>
If you want to check if the checkbox is checked:
<script>
function displayResult()
{
var x=document.getElementById("checkboxid");
alert(x.checked);
}
</script>
and in your body:
<button type="button" onclick="displayResult()">Display value</button>
I'm trying to write a piece of code which use the user choice in a form.
The code should give an alert window with the name of the radio selected but doesn't work, it only show the A alert either A is selector or B is selected.
This is the form
<FORM>
<input type="radio" name="search_type" value="A"/>type A<br/>
<input type="radio" name="search_type" value="B"/>type B<br/>
</FORM>
and this is the js code
$(document).ready(function(){
$('input:radio[name="search_type"]').change(function() {
if ($('input:radio[name="search_type"]').val() == 'A'){
alert('type A');
};
if ($('input:radio[name="search_type"]').val() == 'B'){
alert('type B');
};
});
});
Here you can find the running code: http://jsfiddle.net/ur7cc/
Can anybody please tell me why it isn't working?
Thanks!
You need to use with :checked selector for .val() when dealing with radio/checkbox. Alternatively you can use $(this).val() where this is basically the radio that triggered the change. See below,
$(document).ready(function(){
$('input:radio[name="search_type"]').change(function() {
if ($(this).val() == 'A'){
alert('type A');
}
if ($(this).val() == 'B'){
alert('type B');
}
});
});
To use with :checked selector,
$('input:radio[name="search_type"]:checked').val()
DEMO: http://jsfiddle.net/skram/ur7cc/1/
use $(this) instead.
Here is a simplified version.
$(document).ready(function(){
$('input:radio[name="search_type"]').change(function() {
alert("Type: "+$(this).val());
});
});
DEMO: http://jsfiddle.net/ur7cc/2/
This is a working code that I wrote and tested. It works. It writes out the status of the checkbox in a different one. Give it a shot. It worked for me.
<input type="radio" onclick="alert(this.name);" name="A"/> button A<br>
<input type="radio" onclick="alert(this.name);" name="B"/> button B<br>
I hope it helps!
The $('input:radio[name="search_type"]') selector returns an array object. You are overcomplicating this. No need to use it again. Here is much simpler method using the retrieved object:
$(document).ready(function(e) {
$('input:radio[name="search_type"]').change(function() {
alert ("type "+$(this).val());
})
})
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>