Check if at least one checkbox is checked using jQuery - javascript

I have five checkboxes. Using jQuery, how do I check if at least one of them is checked?
<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">

is() can do this, and is arguably the only acceptable use of is(":checked"):
From the jQuery docs, http://api.jquery.com/is/:
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
alert($("input[name='service[]']").is(":checked"));
Example: http://jsfiddle.net/AndyE/bytVX/1/ (based on the fiddle by Brandon Gano)
Alternatively, and potentially faster, you can pass a function to is():
$("input[name='service[]']").is(function () {
return this.checked;
});

This should do the trick:
function isOneChecked() {
return ($('[name="service[]"]:checked').length > 0);
}

Edit: The original solution in this answer is inefficient and should not be used. Please see the revised solution based on comments and examples from other answers to this question.
The original (bad) solution follows:
// DO NOT USE; SEE BELOW
$('button').click(function () {
var atLeastOneIsChecked = false;
$('input:checkbox').each(function () {
if ($(this).is(':checked')) {
atLeastOneIsChecked = true;
// Stop .each from processing any more items
return false;
}
});
// Do something with atLeastOneIsChecked
});
The use of .each() is redundant in this example, as .is() can be used directly on the set of objects rather than manually iterating through each one. A more efficient solution follows:
$('button').click(function () {
var atLeastOneIsChecked = $('input:checkbox').is(':checked');
// Do something with atLeastOneIsChecked
});
Note that one of the comments indicates a strong dislike for $(this).is(':checked'). To clarify, there is nothing wrong with is(':checked') in cases where you are testing a set of objects. That said, calling is(':checked') on a single item is much less efficient than calling .checked on the same item. It also involves an unnecessary call to the $ function.

Another answer:
!!$("[type=checkbox]:checked").length
or
!!$("[name=service[]]:checked").length
It depends on what you want.

var checkboxes = document.getElementsByName("service[]");
if ([].some.call(checkboxes, function () { return this.checked; })) {
// code
}
What you want is simple, get all the elements with the name, then run some code if some of those elements are checked.
No need for jQuery.
You may need an ES5 shim for legacy browsers though

You should try like this....
var checkboxes = $("input[type='checkbox']"),
submitButt = $("input[type='submit']");
checkboxes.click(function() {
submitButt.attr("disabled", !checkboxes.is(":checked"));
});

you need to check if checkbox is checked or not.
$("#select_all").click(function(){
var checkboxes = $("input[type='checkbox']");
if(checkboxes.is(":checked"))
alert("checked");
else
alert("select at least one;
});

var atLeastOneIsChecked = $('input[name="service[]"]:checked').length > 0;

The square bracket [] is not necessary:
var atLeastOneIsChecked = $("input[name='service']:checked").length > 0;
The same goes to your HTML, but better to have an id to uniquely identify each of the checkboxes:
<input id="chk1" type="checkbox" name="service">
<br />
<input id="chk2" type="checkbox" name="service">
<br />
<input id="chk3" type="checkbox" name="service">
<br />
<input id="chk4" type="checkbox" name="service">
<br />
<input id="chk5" type="checkbox" name="service">

You can do the following way. Initially set a variable, lets say checked as false. Then set it to true if the following condition met. Use an if statement to check the variable. Take note: Here submit is the id of the button, main is the id of the form.
$("#submit").click(function() {
var checked = false;
if (jQuery('#main input[type=checkbox]:checked').length) {
checked = true;
}
if (!checked) {
//Do something
}
});

Related

Check one checkbox when other is selected [duplicate]

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;
});
}
});

Submit form only if at least one checkbox is checked

i'm triyng to validate a form.
In this form you've to choose at least one element by checkboxes, and I can't be sure about their quantity (it depends by elements number).
I need to enable the submit input if one or more checkboxes are checked, and disable it if there aren't any checkbox checked, how can I do?
Here's my code:
<form id="booking">
<input type="checkbox" name="room1" class="roomselect"/>
<input type="checkbox" name="room2" class="roomselect"/>
<input type="checkbox" name="room3" class="roomselect"/>
<input type="submit" value="Request" id="subm" />
</form>
//dom ready handler
jQuery(function ($) {
//form submit handler
$('#booking').submit(function (e) {
//check atleat 1 checkbox is checked
if (!$('.roomselect').is(':checked')) {
//prevent the default form submit if it is not checked
e.preventDefault();
}
})
})
You can use :checked selector along with .length to find checked checkbox count:
var len = $(".roomselect:checked").length;
if(len>0){
//more than one checkbox is checked
}
Demo
The :checked selector will Match all elements that are checked or selected.
You could try this
$("#subm").click(function(e){
if($(".roomselect:checked").length == 0){
e.preventDefault();
}
});
i suggest you to use "button" instead of "submit".
please follow this
HTML->
<form id="booking" action="https://www.google.co.in/search">
<input type="checkbox" value="facebook" name="q"/>
<input type="checkbox" value="gmail" name="q"/>
<input type="checkbox" value="stackoverflow" name="q"/>
<input type="button" value="Request" id="submit" />
$(function(){
$("#submit").click(function(e){
var number_of_checked_checkbox= $("input[name=q]:checked").length;
if(number_of_checked_checkbox==0){
alert("select any one");
}else{
$("#booking").submit();
}
});
});
Vanilla JavaScript equivalent of the jQuery way, using document.querySelector
if (document.querySelector('.roomselect:checked')) {
// somethings checked
}
Demo
The easiest method would be with javascript, fortunately someone's already done all the work here (with jQuery). All you'd need to do to adapt that example is to change #form_check to #booking.
Essentially what that example is doing is forcing itself before the submit action when it sees one is being tried for the form then it's searching inside the form element for any checkbox elements with a checked state and if it can't find any is sending a preventdefault to stop whatever the client/browser's default response to a submit action request would be or otherwise just sending as normal.
Also regarding the other answers, using === is more secure and returning false gives you some redundancy. Here's some discussion on what the return false adds.
Additionally don't use click() for this as you potentially run into use cases where you're technically submitting the form but aren't actually clicking it, like say when you hit enter
try this
var checked = false;
$(function(){
$('#subm').click(function(e){
checkall();
if(!checked){
e.preventDefault();
}
});
$('.roomselect').change(function(e){
checkall();
});
checkall();
});
function checkall()
{
checked = $('.roomselect:checked').length > 0;
$('#subm').prop('disabled',!checked);
}
$("#form_id").submit(function(e) {
var totalChecked = $('#div_id:input[type="checkbox"]:checked').length;
if(totalChecked < 1)
{
alert('Please select at least one checkbox before submit');
return false;
}
});

How to enable radio group by checkbox?

I did search all over but i still cant fix it. Please help:
Here is my js code:
<script type="text/javascript">
$(document).ready(function() {
$("#email_acc").click(function() {
if ( $(this).is(":checked") ) {
$("#email_group").attr("enabled","enabled");
}
});
$("#system_acc").click(function() {
if ( $(this).is(":checked") ) {
$("#system_group").attr("enabled","enabled");
}
});
});
</script>
The following shows my html code:
<input type="checkbox" name="email_acc" id="email_acc" />Email Account
<input type="checkbox" name="sys_acc" id="sys_acc" />System Account
<input type="radio" name="radio_email" value="create" class="email_group" id="radio_email_0" disabled="disabled"/>New
<input type="radio" name="radio_email" value="change" id="radio_email_1" disabled="disabled"/>Change
<input type="radio" name="radio_email" value="terminate" id="radio_email_2" disabled="disabled"\ />Termination
<input type="radio" name="radio_system" value="create" class="system_group" id="radio_system_0" disabled="disabled"/>New
<input type="radio" name="radio_system" value="change" id="radio_system_1" disabled="disabled" />Change
<input type="radio" name="radio_system" value="terminate" id="radio_system_2" disabled="disabled" />Termination
I donno what is the problem.It just doesn't work.
$(document).ready(function()
{
$("#email_acc").click(function()
{
if ( $(this).is(":checked") )
{
$("input[name='radio_email']").removeAttr("disabled");
// ^----------------enable all the checkbox with common name
}
});
$("#sys_acc").click(function()
// ^---------corrected id
{
if ( $(this).is(":checked") )
{ $("input[name='radio_system']").removeAttr("disabled");
// ^----------------enable all the checkbox with common name
}
});
});​
DEMO
DEMO 2
Code updated for new requirements from OP, cleaned code thanks to nnnnnn
UPDATED DEMO 3
There is no "enabled" attribute or property, just a "disabled" attribute or property which can be set to false to enable the element(s) in question. (The "attribute" is in your source html, but dynamic changes are made to the "property", setting it to a boolean value to disable or not.)
Unless using an old version of jQuery, you should use the .prop() method to update this property. To enable the whole group of radio buttons you have to select them all by their name attribute (or give them a common class and select by that).
$("#email_acc").click(function() {
if ( this.checked ) {
$('input[name="radio_email"]').prop('disabled', false);
}
});
// and the same for the other checkbox and group.
Note that your second checkbox has an id="sys_acc" but your JS is trying to select with "#system_acc" - you need to make sure they match.
If you need to disable the group again if the checkbox is unchecked then you can do the following, removing the if statement and setting the disabled property to the inverse of the checked property:
$('#email_acc').click(function() {
$('input[name="radio_email"]').prop('disabled', !this.checked);
});
// and again the same idea for the other checkbox and group.
Demo: http://jsfiddle.net/UqTB3/
Note that in both cases I've used this.checked instead of $(this).is(":checked"): I find the former easier to read, and it is more efficient to check the DOM element's checked property directly than to create a jQuery object and use .is(":checked"). But if you're really keen on using jQuery for everything you can make the appropriate substitution.
$("#email_acc").click(function()
{
if ( $(this).is(":checked") )
{
$("#email_group").attr("disabled","false");
or
$("#email_group").attr("disabled",false);
}
});
Add name in input html
name should be the same
<script type="text/javascript">
document.getElementById('cek3').onchange = function () {
document.getElementById('fasilitas_kost1').disabled = !this.checked;
document.getElementById('fasilitas_kost2').disabled = !this.checked;
document.getElementById('fasilitas_kost3').disabled = !this.checked;
document.getElementById('fasilitas_kost4').disabled = !this.checked;
document.getElementById('fasilitas_kost5').disabled = !this.checked;
document.getElementById('fasilitas_kost6').disabled = !this.checked;
document.getElementById('fasilitas_kost7').disabled = !this.checked;
};
</script>

Change/Get check state of CheckBox

I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.
JavaScript function
function checkAddress()
{
if (checkAddress.checked == true)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onchange="checkAddress()" />
Using onclick instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.
You also need to pass the checkbox into the function:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
You need to retrieve the checkbox before using it.
Give the checkbox an id attribute to retrieve it with document.getElementById(..) and then check its current state.
For example:
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
// ..
}
}
And your HTML would then look like this:
<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>
(Also changed the onchange to onclick. Doesn't work quite well in IE :).
I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.
function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.
if(document.getElementById(from).checked==true)
//checks status of "from" element. change to whatever validation you prefer.
{
document.getElementById(to).checked=true;
//if validation returns true, checks target checkbox
}
else
{
document.getElementById(to).checked=false;
//if validation returns true, unchecks target checkbox
}
}
HTML being something like
<input type="radio" name="bob" onclick="copycheck('from','to');" />
where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to".
As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.
Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.
Hope this helps.
You need this:
window.onload = function(){
var elCheckBox=document.getElementById("cbxTodos");
elCheckBox.onchange =function (){
alert("como ves");
}
};
Needs to be:
if (document.forms[0].elements["checkAddress"].checked == true)
Assuming you have one form, otherwise use the form name.
As a side note, don't call the element and the function in the same name it can cause weird conflicts.
<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
I know this is late info, but in jQuery, using .checked is possible and easy!
If your element is something like:
<td>
<input type="radio" name="bob" />
</td>
You can easily get/set checked state as such:
$("td").each(function()
{
$(this).click(function()
{
var thisInput = $(this).find("input[type=radio]");
var checked = thisInput.is(":checked");
thisInput[0].checked = (checked) ? false : true;
}
});
The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object!
ENJOY!
This is an example of how I use this kind of thing:
HTML :
<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">
JAVASCRIPT :
function ThisIsTheFunction(temp,temp2) {
if(temp2 == true) {
document.getElementById(temp).style.visibility = "visible";
} else {
document.getElementById(temp).style.visibility = "hidden";
}
}
var val = $("#checkboxId").is(":checked");
Here is a quick implementation with samples:
Checkbox to check all items:
<input id="btnSelectAll" type="checkbox">
Single item (for table row):
<input class="single-item" name="item[]" type="checkbox">
Js code for jQuery:
$(document).on('click', '#btnSelectAll', function(state) {
if ($('#btnSelectAll').is(':checked')) {
$('.single-item').prop('checked', true);
$('.batch-erase').addClass('d-block');
} else {
$('.single-item').prop('checked', false);
$('.batch-erase').removeClass('d-block');
}
});
Batch delete item:
<div class="batch-erase d-none">
<a href="/path/to/delete" class="btn btn-danger btn-sm">
<i class="fe-trash"></i> Delete All
</a>
</div>
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});

How do I check whether a checkbox is checked in jQuery?

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.

Categories

Resources