Check Checkbox Disabled (Jquery) - javascript

The purpose is to;
If checkbox is disabled, do nothing.
If checkbox is enabled and checked, set the style of a button.
Here is what I've got so far;
$(document).ready(function (e) {
$(".checkbox").live("click", function () {
if ($(this).hasAttribute('disabled')) {
return false;
}
var isAnyChecked;
$("input[type=checkbox]").each(function () {
var checkedValue = $(this).attr("checked");
if (checkedValue == "checked") {
isAnyChecked = true;
}
});
if (isAnyChecked) {
$("#<%= btnConfirm.ClientID %>").css("display", "block");
} else {
$("#<%= btnConfirm.ClientID %>").css("display", "none");
}
}); });
I've tried .is(':disabled'), .hasAttr(), .prop() and .attr(). Any help would be greatly appreciated.

You have to check whether the disabled attribute is true: .attr('disabled').
Or, better, use .is(':disabled').---
EDIT: So it seems that .attr is now deprecated for this use (see http://api.jquery.com/attr/)
The preferred way is:
$('#myCheckbox').prop('disabled')
It has to be noted that this still work as of today:
$('#myCheckbox').is(':disabled')
Try it here: https://jsfiddle.net/Robloche/phaqfrmj/

Also you can try use this:
$("#myCheckBox").is('[disabled]');
Works for me to determine if an element is disabled.
Possible others solutions (.disabled, .is(':disabled'), .attr('disabled'), .prop('disabled')).

for me, this works like a charm to disable:
$("#myCheckBox").prop("disabled", true)
to enable:
$("#myCheckBox").prop("disabled", false)

Related

JS overides check in the checkbox on toggle [duplicate]

I'm using Jquery's toggle event to do some stuff when a user clicks a checkbox, like this:
$('input#myId').toggle(
function(){
//do stuff
},
function(){
//do other stuff
}
);
The problem is that the checkbox isn't being ticked when I click on the checkbox. (All the stuff I've put into the toggle event is working properly.)
I've tried the following:
$('input#myId').attr('checked', 'checked');
and
$(this).attr('checked', 'checked');
and even simply
return true;
But nothing is working. Can anyone tell me where I'm going wrong?
Edit - thanks to all who replied. Dreas' answer very nearly worked for me, except for the part that checked the attribute. This works perfectly (although it's a bit hacky)
$('input#myInput').change(function ()
{
if(!$(this).hasClass("checked"))
{
//do stuff if the checkbox isn't checked
$(this).addClass("checked");
return;
}
//do stuff if the checkbox isn't checked
$(this).removeClass('checked');
});
Thanks again to all who replied.
Use the change event instead of the toggle event, like such:
$('input#myId').change(function () {
if ($(this).attr("checked")) {
//do the stuff that you would do when 'checked'
return;
}
//Here do the stuff you want to do when 'unchecked'
});
While using the change event handler suggested by Dreas Grech is appropriate, it doesn't work well in IE 6 & 7, which doesn't fire the change event until the focus is blurred (that is, until you click outside the area of the checkbox). As QuirksMode say, "it's a serious bug".
You might want to use the click event handler, but that won't work with keyboard navigation. You need to register a keyup handler too...
See also this related question.
I haven't yet found a good cross-browser solution that supports both mouse clicks and keyboard activation of the checkboxes (and doesn't fire too many events).
Regarding your solution for checking whether the checkbox is checked or not, instead of adding your own checked class, you may use HTML's checked attribute:
$('input#myInput').change(function () {
if ($(this).attr("checked")) {
//do stuff if the checkbox is checked
} else {
//do stuff if the checkbox isn't checked
}
});
Any browser sets the checked attribute of an input element to the value "checked" if the checkbox is checked, and sets it to null (or deletes the attribute) if the checkbox is not checked.
why not using $.is() ?
$('input#myId').change(
function() {
if ($(this).is(':checked')) {
// do stuff here
} else {
// do other stuff here
}
});
This is an answer by MorningZ (I found it here) that makes totally sense:
The part you are missing is that "checkbox" is a jQuery object, not a
checkbox DOM object
so:
checkbox.checked sure would error because there is no .checked property of a jQuery
object
so:
checkbox[0].checked would work since the first item on a jQuery array is the DOM object
itself.
So in your change() function you can use
$(this)[0].checked
$('input#myId').toggle(
function(e){
e.preventDefault();
//do stuff
$(this).attr('checked', 'true');
},
function(e){
e.preventDefault();
//do other stuff
$(this).attr('checked', 'false');
}
);
this worked for me............ check it
$(":checkbox").click(function(){
if($(this).attr("id").split("chk_all")[1])
{
var ty = "sel"+$(this).attr("id").split("chk_all")[1]+"[]";
if($(this).attr("checked"))
{
$('input[name="'+ty+'"]').attr("checked", "checked");
}
else
{
$('input[name="'+ty+'"]').removeAttr("checked");
}
}
})
I did a similar approach but simply using the checked attribute such as
//toggles checkbox on/off
$("input:checkbox").change(
function(){
if(!this.checked){
this.checked=true;
}
else{
this.checked=false;
}
}
);
//end toggle
$("input[type=checkbox][checked=false]")// be shure to set to false on ready
$("input#Checkbox1").change(function() {
if ($(this).attr("checked")) {
$("#chk1").html("you just selected me")//the lable
} else {$("#chk1").html("you just un selected me") }
});
Try using a non-jquery function:
function chkboxToggle() {
if ($('input#chkbox').attr('checked'))
// do something
else
// do something else
}
then in your form:
<input id="chkbox" type="checkbox" onclick="chkboxToggle()" />
Try:
$(":checkbox").click(function(){
if($(this).attr("checked"))
{
$('input[name="name[]"]').attr("checked", "checked");
}
else
{
$('input[name="name[]"]').removeAttr("checked");
}
})

javascript/jquery: hide and uncheck, checked option/options [duplicate]

I'd like to do something like this to tick a checkbox using jQuery:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
Does such a thing exist?
Modern jQuery
Use .prop():
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
DOM API
If you're working with just one element, you can always just access the underlying HTMLInputElement and modify its .checked property:
$('.myCheckbox')[0].checked = true;
$('.myCheckbox')[0].checked = false;
The benefit to using the .prop() and .attr() methods instead of this is that they will operate on all matched elements.
jQuery 1.5.x and below
The .prop() method is not available, so you need to use .attr().
$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);
Note that this is the approach used by jQuery's unit tests prior to version 1.6 and is preferable to using $('.myCheckbox').removeAttr('checked'); since the latter will, if the box was initially checked, change the behaviour of a call to .reset() on any form that contains it – a subtle but probably unwelcome behaviour change.
For more context, some incomplete discussion of the changes to the handling of the checked attribute/property in the transition from 1.5.x to 1.6 can be found in the version 1.6 release notes and the Attributes vs. Properties section of the .prop() documentation.
Use:
$(".myCheckbox").attr('checked', true); // Deprecated
$(".myCheckbox").prop('checked', true);
And if you want to check if a checkbox is checked or not:
$('.myCheckbox').is(':checked');
This is the correct way of checking and unchecking checkboxes with jQuery, as it is cross-platform standard, and will allow form reposts.
$('.myCheckBox').each(function(){ this.checked = true; });
$('.myCheckBox').each(function(){ this.checked = false; });
By doing this, you are using JavaScript standards for checking and unchecking checkboxes, so any browser that properly implements the "checked" property of the checkbox element will run this code flawlessly. This should be all major browsers, but I am unable to test previous to Internet Explorer 9.
The Problem (jQuery 1.6):
Once a user clicks on a checkbox, that checkbox stops responding to the "checked" attribute changes.
Here is an example of the checkbox attribute failing to do the job after someone has clicked the checkbox (this happens in Chrome).
Fiddle
The Solution:
By using JavaScript's "checked" property on the DOM elements, we are able to solve the problem directly, instead of trying to manipulate the DOM into doing what we want it to do.
Fiddle
This plugin will alter the checked property of any elements selected by jQuery, and successfully check and uncheck checkboxes under all circumstances. So, while this may seem like an over-bearing solution, it will make your site's user experience better, and help prevent user frustration.
(function( $ ) {
$.fn.checked = function(value) {
if(value === true || value === false) {
// Set the value of the checkbox
$(this).each(function(){ this.checked = value; });
}
else if(value === undefined || value === 'toggle') {
// Toggle the checkbox
$(this).each(function(){ this.checked = !this.checked; });
}
return this;
};
})( jQuery );
Alternatively, if you do not want to use a plugin, you can use the following code snippets:
// Check
$(':checkbox').prop('checked', true);
// Un-check
$(':checkbox').prop('checked', false);
// Toggle
$(':checkbox').prop('checked', function (i, value) {
return !value;
});
You can do
$('.myCheckbox').attr('checked',true) //Standards compliant
or
$("form #mycheckbox").attr('checked', true)
If you have custom code in the onclick event for the checkbox that you want to fire, use this one instead:
$("#mycheckbox").click();
You can uncheck by removing the attribute entirely:
$('.myCheckbox').removeAttr('checked')
You can check all checkboxes like this:
$(".myCheckbox").each(function(){
$("#mycheckbox").click()
});
You can also extend the $.fn object with new methods:
(function($) {
$.fn.extend({
check : function() {
return this.filter(":radio, :checkbox").attr("checked", true);
},
uncheck : function() {
return this.filter(":radio, :checkbox").removeAttr("checked");
}
});
}(jQuery));
Then you can just do:
$(":checkbox").check();
$(":checkbox").uncheck();
Or you may want to give them more unique names like mycheck() and myuncheck() in case you use some other library that uses those names.
$("#mycheckbox")[0].checked = true;
$("#mycheckbox").attr('checked', true);
$("#mycheckbox").click();
The last one will fire the click event for the checkbox, the others will not.
So if you have custom code in the onclick event for the checkbox that you want to fire, use the last one.
To check a checkbox you should use
$('.myCheckbox').attr('checked',true);
or
$('.myCheckbox').attr('checked','checked');
and to uncheck a check box you should always set it to false:
$('.myCheckbox').attr('checked',false);
If you do
$('.myCheckbox').removeAttr('checked')
it removes the attribute all together and therefore you will not be able to reset the form.
BAD DEMO jQuery 1.6. I think this is broken. For 1.6 I am going to make a new post on that.
NEW WORKING DEMO jQuery 1.5.2 works in Chrome.
Both demos use
$('#tc').click(function() {
if ( $('#myCheckbox').attr('checked')) {
$('#myCheckbox').attr('checked', false);
} else {
$('#myCheckbox').attr('checked', 'checked');
}
});
This selects elements that have the specified attribute with a value containing the given substring "ckbItem":
$('input[name *= ckbItem]').prop('checked', true);
It will select all elements that contain ckbItem in its name attribute.
Assuming that the question is...
How do I check a checkbox-set BY VALUE?
Remember that in a typical checkbox set, all input tags have the same name, they differ by the attribute value: there are no ID for each input of the set.
Xian's answer can be extended with a more specific selector, using the following line of code:
$("input.myclass[name='myname'][value='the_value']").prop("checked", true);
I'm missing the solution. I'll always use:
if ($('#myCheckBox:checked').val() !== undefined)
{
//Checked
}
else
{
//Not checked
}
To check a checkbox using jQuery 1.6 or higher just do this:
checkbox.prop('checked', true);
To uncheck, use:
checkbox.prop('checked', false);
Here' s what I like to use to toggle a checkbox using jQuery:
checkbox.prop('checked', !checkbox.prop('checked'));
If you're using jQuery 1.5 or lower:
checkbox.attr('checked', true);
To uncheck, use:
checkbox.attr('checked', false);
Here is a way to do it without jQuery
function addOrAttachListener(el, type, listener, useCapture) {
if (el.addEventListener) {
el.addEventListener(type, listener, useCapture);
} else if (el.attachEvent) {
el.attachEvent("on" + type, listener);
}
};
addOrAttachListener(window, "load", function() {
var cbElem = document.getElementById("cb");
var rcbElem = document.getElementById("rcb");
addOrAttachListener(cbElem, "click", function() {
rcbElem.checked = cbElem.checked;
}, false);
}, false);
<label>Click Me!
<input id="cb" type="checkbox" />
</label>
<label>Reflection:
<input id="rcb" type="checkbox" />
</label>
Here is code for checked and unchecked with a button:
var set=1;
var unset=0;
jQuery( function() {
$( '.checkAll' ).live('click', function() {
$( '.cb-element' ).each(function () {
if(set==1){ $( '.cb-element' ).attr('checked', true) unset=0; }
if(set==0){ $( '.cb-element' ).attr('checked', false); unset=1; }
});
set=unset;
});
});
Update: Here is the same code block using the newer Jquery 1.6+ prop method, which replaces attr:
var set=1;
var unset=0;
jQuery( function() {
$( '.checkAll' ).live('click', function() {
$( '.cb-element' ).each(function () {
if(set==1){ $( '.cb-element' ).prop('checked', true) unset=0; }
if(set==0){ $( '.cb-element' ).prop('checked', false); unset=1; }
});
set=unset;
});
});
Try this:
$('#checkboxid').get(0).checked = true; //For checking
$('#checkboxid').get(0).checked = false; //For unchecking
We can use elementObject with jQuery for getting the attribute checked:
$(objectElement).attr('checked');
We can use this for all jQuery versions without any error.
Update: Jquery 1.6+ has the new prop method which replaces attr, e.g.:
$(objectElement).prop('checked');
If you are using PhoneGap doing application development, and you have a value on the button that you want to show instantly, remember to do this
$('span.ui-[controlname]',$('[id]')).text("the value");
I found that without the span, the interface will not update no matter what you do.
Here is the code and demo for how to check multiple check boxes...
http://jsfiddle.net/tamilmani/z8TTt/
$("#check").on("click", function () {
var chk = document.getElementById('check').checked;
var arr = document.getElementsByTagName("input");
if (chk) {
for (var i in arr) {
if (arr[i].name == 'check') arr[i].checked = true;
}
} else {
for (var i in arr) {
if (arr[i].name == 'check') arr[i].checked = false;
}
}
});
Another possible solution:
var c = $("#checkboxid");
if (c.is(":checked")) {
$('#checkboxid').prop('checked', false);
} else {
$('#checkboxid').prop('checked', true);
}
As #livefree75 said:
jQuery 1.5.x and below
You can also extend the $.fn object with new methods:
(function($) {
$.fn.extend({
check : function() {
return this.filter(":radio, :checkbox").attr("checked", true);
},
uncheck : function() {
return this.filter(":radio, :checkbox").removeAttr("checked");
}
});
}(jQuery));
But in new versions of jQuery, we have to use something like this:
jQuery 1.6+
(function($) {
$.fn.extend({
check : function() {
return this.filter(":radio, :checkbox").prop("checked", true);
},
uncheck : function() {
return this.filter(":radio, :checkbox").prop("checked",false);
}
});
}(jQuery));
Then you can just do:
$(":checkbox").check();
$(":checkbox").uncheck();
If using mobile and you want the interface to update and show the checkbox as unchecked, use the following:
$("#checkbox1").prop('checked', false).checkboxradio("refresh");
For jQuery 1.6+
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
For jQuery 1.5.x and below
$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);
To check,
$('.myCheckbox').removeAttr('checked');
To check and uncheck
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
Be aware of memory leaks in Internet Explorer prior to Internet Explorer 9, as the jQuery documentation states:
In Internet Explorer prior to version 9, using .prop() to set a DOM
element property to anything other than a simple primitive value
(number, string, or boolean) can cause memory leaks if the property is
not removed (using .removeProp()) before the DOM element is removed
from the document. To safely set values on DOM objects without memory
leaks, use .data().
$('controlCheckBox').click(function(){
var temp = $(this).prop('checked');
$('controlledCheckBoxes').prop('checked', temp);
});
This is probably the shortest and easiest solution:
$(".myCheckBox")[0].checked = true;
or
$(".myCheckBox")[0].checked = false;
Even shorter would be:
$(".myCheckBox")[0].checked = !0;
$(".myCheckBox")[0].checked = !1;
Here is a jsFiddle as well.
Plain JavaScript is very simple and much less overhead:
var elements = document.getElementsByClassName('myCheckBox');
for(var i = 0; i < elements.length; i++)
{
elements[i].checked = true;
}
Example here
I couldn't get it working using:
$("#cb").prop('checked', 'true');
$("#cb").prop('checked', 'false');
Both true and false would check the checkbox. What worked for me was:
$("#cb").prop('checked', 'true'); // For checking
$("#cb").prop('checked', ''); // For unchecking
When you checked a checkbox like;
$('.className').attr('checked', 'checked')
it might not be enough. You should also call the function below;
$('.className').prop('checked', 'true')
Especially when you removed the checkbox checked attribute.
Here's the complete answer
using jQuery
I test it and it works 100% :D
// when the button (select_unit_button) is clicked it returns all the checed checkboxes values
$("#select_unit_button").on("click", function(e){
var arr = [];
$(':checkbox:checked').each(function(i){
arr[i] = $(this).val(); // u can get id or anything else
});
//console.log(arr); // u can test it using this in google chrome
});
In jQuery,
if($("#checkboxId").is(':checked')){
alert("Checked");
}
or
if($("#checkboxId").attr('checked')==true){
alert("Checked");
}
In JavaScript,
if (document.getElementById("checkboxID").checked){
alert("Checked");
}

jQuery Plugin - Strange click behaviour

I have written a short plugin for jQuery which will change the styles of the browser's in-built checkbox, so that it better fits with the theme.
Here is the plugin code:
(function ($) {
$.fn.checkbox = function()
{
var uiBox = $('<span class="ui-checkbox" />'),
that = this;
uiBox.data('checkbox', this).insertAfter(this);
this.hide();
if(this.is(':disabled')) { uiBox.addClass('disabled'); }
if(this.is(':checked')) { uiBox.addClass('checked'); }
if(!uiBox.hasClass('disabled'))
{
uiBox.on('click', function() {
var checkbox = $(this).data('checkbox');
if(checkbox.is(':checked'))
{
uiBox.removeClass('checked');
checkbox.attr('checked', false);
}
else
{
uiBox.addClass('checked');
checkbox.attr('checked', 'checked');
}
});
}
};
} (jQuery));
This code is then in turn called through the DOMReady handler using:
$('input[type="checkbox"].ui').checkbox();
Everything works the first three times the 'checkbox' is clicked, but thereafter for some reason the code no longer executes the addition / removal of the necessary classes, and the original checkbox is never updated. Can anyone shed any light on the situation, and explain why this is happening?
jsFiddle Demo
It's because you're using attr() and not prop(), changing just the attribute and not the underlying property, change it to
checkbox.prop('checked', true);
FIDDLE
Use .prop() instead of .attr()
checkbox.prop('checked', 'checked');
Demo
Use this following code, I have tried it in your fiddle example it is working there,
checkbox.prop('checked', true);
Hope this Helps!

Get radio button by name in a loop using jQuery

I'm using jquery 1.4.1 and while I plan to upgrade soon, I need to resolve the below issue. I need to loop over all the radio buttons on my html page and then do some logic for a couple of radio button's based on their name. Below was my attempt but it's not working, any ideas?
jQuery('input:radio').each(function() {
if(jQuery(this).name('radioOneName')) {
alert("radioOneName")
} else {
alert("not radioOneName")
}
});
Try this jQuery(this).attr('name') === 'radioOneName'. Link to docs.
Try this :)
$(document).ready(function () {
$(':radio').each(function () {
var myval = $(this).val();
if (myval == "button1")
{
alert("first");
}
else
{
alert("second");
}
});
});
You should be using
$(this).attr("name");
Glad I could help.
You can try this:
<input type="radio" id="abc" name="myradioname"/>
and in javascript using this:
$('input[name="myradioname"]').each(function(){
// do something...
})
Basically, this syntax queries the document for the <input> tag having the specified name.

disable a CheckBox depending on dropdownlist

I'm working on a asp.net mvc3 application with DropDownLists and CheckBoxes and so on.
I wrote a javascript to disable a CheckBox if a defined option of a dropdownlist is selected:
$(function() {
$('#dropdownlistId').change(function() {
if (this.value == '1st option') {
$('#checkboxId').attr('disabled', disabled);
} else {
$('#checkboxId').removeAttr('disabled', disabled);
}
});
});
this works fine, but the script reacts only on a change of the dropdownlist
so if '1st option' is on the top of the dropdownlist and so automatically selected as default, the script doesn't disable the checkbox. Only if the user select another option and select '1st option' once again...
Please help me :)
PS: the script also doesn't work if I use my keyboard to switch the dropdownlist options instead of my mouse
So it would be very kind if you could help my to improve the script, because I really can't do javascript :/
$(function() {
var $cb = $('#checkboxId');
$('#dropdownlistId').change(function() {
if (this.value == '1st option') {
$cb.prop('disabled', true);
} else {
$cb.prop('disabled', false);
}
}).trigger('change');
});
The difference in triggering change event after adding halnderl. About your second question - Using keyboard the 'change' event will be triggered when select will lose focus ('blur').
You could do something like this:
function setCheckBox() {
if (this.value == '1st option') {
$('#checkboxId').attr('disabled', disabled);
} else {
$('#checkboxId').removeAttr('disabled', disabled);
}
}
$(function() {
setCheckBox();//do this on load..
$('#dropdownlistId').change(function() {
setCheckBox();//and on change
});
});
When you define your CheckBox control, use disabled attribute to disable it by default. That way it will be disabled already and there is no need to add more javascript to disable it from the get go.
It would look something like this:
#Html.CheckBoxFor(model => model.IsCheckBox, new { #disabled = "true" })
$(function() {
var $cb = $('#checkboxId');
$('#dropdownlistId').change(function() {
if (this.value == '1st option') {
$cb.attr('disabled', disabled);
} else {
$cb.removeAttr('disabled', disabled);
}
}).trigger('change');
});
works like a charm now
thank you guys
Your code seems to be little incorrect depends on your need because your calling the disable function on change of that dropdown list you need to write it in document.ready like this
$(document).ready(function () {if(document.getElementById("dropdownlistId").value="1stoption")
{
document.getElementById('checkboxId').style.visibility = 'hidden';
}
else
{//do something whatever you wish here in else condition
}
}
Hope it helps!!!

Categories