I need to check the checked property of a checkbox and perform the 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 gives false as by default:
if ($('#isAgeSelected').attr('checked')) {
$("#txtAge").show();
}
else
{
$("#txtAge").hide();
}
Did I miss anything here?
Source: Tips4all
Try this:
ReplyDeleteif ($('#isAgeSelected').is(':checked')) { $("#txtAge").show(); } else { $("#txtAge").hide(); }
You can shorten this using ternary, some might say it's a bit less readable, but that's how I would do it:
$('#isAgeSelected').is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
EDIT (14 months later): There's a much prettier way to do this, using toggle:
$('#isAgeSelected').click(function() {
$("#txtAge").toggle(this.checked);
});
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>
Demo: http://jsfiddle.net/5udtC/
Use Jquery is() function
ReplyDeleteif($("#isAgeSelected").is(':checked'))
$("#txtAge").show();
else
$("#txtAge").hide();
This worked for me.
ReplyDelete$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 MicrosoftAjax, not jQuery
Using jQuery > 1.6
ReplyDelete<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
}
I am using this and this is working absolutely fine:
ReplyDeleteif($("#checkkBoxId").attr("checked")==true)
{
alert("Checked");
}
else
{
alert("Unchecked");
}
Note: If the checkbox is checked it will return true otherwise undefined, so better check for the "TRUE" value.
I decided to post an answer on how to do that exact same thing without jQuery. Just because I'm a rebel.
ReplyDeletevar 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.
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).
ReplyDelete$('#isAgeSelected').bind('change', function () {
if ($(this).is(':checked'))
$("#txtAge").show();
else
$("#txtAge").hide();
});
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():
ReplyDelete$("#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")
$(selector).attr('checked') !== undefined
ReplyDeleteThis returns true if the input is checked and false if it not.
I believe you could do this:
ReplyDeleteif ($('#isAgeSelected :checked').size() > 0)
{
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
I ran in to the exact same issue. I have an ASP.NET checkbox
ReplyDelete<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 verified in Firefox 9.0.1 that the following works for catching the state of a checkbox post change:
ReplyDelete$("#mycheckbox").change(function() {
var value = $(this).prop("checked") ? 'true' : 'false';
alert(value);
});
My way of doing this is:
ReplyDeleteif ( $("#checkbox:checked").length ) {
alert("checkbox is checked");
} else {
alert("checkbox is not checked");
}
this works for me,
ReplyDelete/* isAgeSelected being id for checkbox */
$("#isAgeSelected").click(function(){
$(this).is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
});
Here's an example that includes initialising the show/hide to match the state of the checkbox when the page loads; taking account of the fact that firefox remembers the state of checkboxes when you refresh the page, but won't remember the state of the shown/hidden elements.
ReplyDelete$(function() {
// initialise visibility when page is loaded
$('tr.invoiceItemRow').toggle($('#showInvoiceItems').attr('checked'));
// attach click handler to checkbox
$('#showInvoiceItems').click(function(){ $('tr.invoiceItemRow').toggle(this.checked);})
});
(with help from other answers on this question)
I was having the same problem and none of the posted solutions seemed to work and then I found out that it's because ASP.NET renders the CheckBox control as a SPAN with INPUT inside, so the CheckBox ID is actually an ID of a SPAN, not an INPUT, so you should use:
ReplyDelete$('#isAgeSelected input')
rather than
$('#isAgeSelected')
and then all methods listed above should work.
I had the same problem, and got it fixed using @karim79 answer.
ReplyDeleteBut I wanted to go further so that it would do this when the checkbox state was changed again. So here's my example, it might help someone
http://jsfiddle.net/shano/bK8EC/26/
if ($("#checkkBoxId").is(':checked') == true) {
ReplyDeletealert("Checked");
}
else {
alert("Unchecked");
}
if($('#isAgeSelected ').attr('checked')){
ReplyDelete$("#txtAge").show();
}
else {
$("#txtAge").hide();
}
Check out this will work definitely...
I made below code in my form
if($('#yesAttendedWorkshop').attr('checked')){
$("#workshopinfo").show();
}
else if($('#notAttendedWorkshop').attr('checked')){
$("#workshopinfo").hide();
$(':input','#workshopinfo').not(':button, :submit, :reset, :hidden').removeAttr('checked').removeAttr('selected');
$('#workshopinfo input:checkbox').removeAttr('checked');
$('#workshopinfo input:text').val('');
}
else {
$("#workshopinfo").hide();
alert("It seems that your profile is not up-to-date. \n\n Please complete your profile ...");
}