jquery set and remove checked attribute doesn't work, javascript does - javascript

for clarity, let's say that I have a checkbox that I want to check and uncheck using two buttons.
I can check/uncheck the box using basic javascript, but with jquery, as soon as I remove the attribute, I cannot set it back... Any idea why?
I created a basic fiffle to illustrate:
http://jsfiddle.net/2K244/
<button id='button1'>check</button>
<button id='button2'>uncheck</button>
<input type="checkbox" id="myBox1" value="polo" />
<br/>
<button id='button3'>check</button>
<button id='button4'>uncheck</button>
<input type="checkbox" id="myBox2" value="polo" />
<br/>
$(document).ready(function () {
$('#button1').click(function () {
$('#myBox1').attr('checked','checked');
});
$('#button2').click(function () {
$('#myBox1').removeAttr('checked');
});
$('#button3').click(function () {
document.getElementById('myBox2').checked = true;
});
$('#button4').click(function () {
document.getElementById('myBox2').checked = false;
});
});

You should be using .prop() instead. From jQuery's documentation on .attr():
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

You should use .prop() now.
http://jsfiddle.net/2K244/1/
$('#button1').click(function () {
$('#myBox1').prop('checked',true);
});
$('#button2').click(function () {
$('#myBox1').prop('checked', false);
});
$('#button3').click(function () {
$('#myBox2').prop('checked', true);
});
$('#button4').click(function () {
$('#myBox2').prop('checked', false);
});

to uncheck a box, use the prop function. $('#myBox1').prop('checked', false); without quotes on false

I don't understand why yours isn't working, but use this:
$("#myBox1").prop("checked",true);
$("#myBox1").prop("checked",false);
Make sure to have a recent version of jQuery.

The status of the checked state can be modified using the true || false second parameter in the .prop() method.
$('#btn_checked').on('click', function() {
$('#myBox1').prop('checked', true);
});
$('#btn_unchecked').on('click', function() {
$('#myBox1').prop('checked', false);
});
jsFiddle

Related

Grey out and make text box read only using jquery

Hi i want to make a text box turn grey and be made read only when a checkbox is ticked. Currently i am able to get the text box to be made read only but will not turn grey. I would usually use the disabled attribute, however i need the value of the text box still to be sent so the disabled attribute can not be used here as it returns a null value.
jQuery(document).ready(function () {
$("#redflag2").click(function () {
$('#new_contracted_support_hours').attr("readonly", $(this).is(":checked"));
$('#new_contracted_support_hours').addclass("greyba", $(this).is(":checked"));
});
});
css
.greyba{
background-color:rgba(178,178,178,1.00);
}
It should be addClass() not addclass() thus class was not added.
You should use .prop() to set properties and toggleClass(),
As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.
jQuery(document).ready(function () {
$("#redflag2").change(function () {
$('#new_contracted_support_hours')
.prop("readonly", this.checked)
.toggleClass("greyba", this.checked);
});
});
A good read .prop() vs .attr()
jQuery(document).ready(function () {
$("#redflag2").click(function () {
$('#new_contracted_support_hours').attr("readonly", $(this).is(":checked"));
if($(this).is(":checked")){
$('#new_contracted_support_hours').addClass("greyba");
}
});
$("#redflag2").click(function () {
$('#new_contracted_support_hours').attr("readonly", $(this).is(":checked"));
if ($(this).is(":checked")) {
$('#new_contracted_support_hours').addClass("greyba");
}
else{
$('#new_contracted_support_hours').removeClass("greyba");
}
});
.greyba{
background-color:rgba(178,178,178,1.00);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="new_contracted_support_hours" type="text"></input>
<input id="redflag2" type="checkbox"></input>
Why not separate your concerns more clearly, leaving JS for functionality and CSS for styling? As you are usilising the readonly attribute, zero styling intervention is required in your Javascript.
nb. Implementation is indicative only
function setState(){
document.getElementById('field').readOnly = document.getElementById('checkbox').checked;
}
$('#checkbox').on('change', setState); // set state on checkbox change
setState(); // set state on initial load
#field[readonly] {
background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="checkbox" type="checkbox" />
<input id="field" type="text" value="value.." />
<input type="text" id="viewers" name=""/>
You can make readonly by this by using:
$('#viewers').attr('readonly', true);
$('#viewers').css('background-color' , '#DEDEDE');

How to stop event bubbling in jquery?

I'm using some JQ stuff on check box, even if the parent div is clicked. I am toggling the value of check box. Clicking on div is working perfectly but when you click on checkbox the function is called twice. Is there any way to solve this problem? following is my code(Fiddle)
HTML:
<div class="check-unit">
<input type="checkbox" class="check" />
<p class="brandList">Model</p>
</div>
JQ:
$('.check').on('change',function(e){
e.stopImmediatePropagation();
if($(this).is(':checked')){
console.log("checked");
}else{
console.log("unchecked");
}
});
$('.check-unit').on('click',function(e){
var checkbox = $(this).children('.check'),
chhhk= checkbox.attr('checked') ? false : true;
checkbox.attr('checked',chhhk);
$(this).children('.check').change();
});
I've seen eventbubbling problem on stackoverflow, but still confused how to do this. FIDDLE
Only execute the callback on the parent element if the target is not the input
$('.check').on('change',function(e){
if(this.checked){
console.log("checked");
}else{
console.log("unchecked");
}
});
$('.check-unit').on('click',function(e){
if ( ! $(e.target).hasClass('check')) {
$(this).children('.check').prop('checked', function(_,state) {
return !state;
}).trigger('change');
}
});
FIDDLE
As a sidenote, this is what label elements are for!
You need to use .prop() instead of .attr() to set the checked property.
$('.check').on('change', function (e) {
if (this.checked) {
console.log("checked");
} else {
console.log("unchecked");
}
}).click(function (e) {
//prevent clicks in the checksboxes from bubbling up otherwise when you click on the checkbox the state will get toggled again the event will be bubbled to check-unit which will again toggle the state negating the click
e.stopPropagation()
});
$('.check-unit').on('click', function () {
var checkbox = $(this).children('.check'),
//use .is() and checked-selector to check whether the checkbox is checked
chhhk = checkbox.is(':checked');
//use .prop() instead of .attr() & toggle the checked state
checkbox.prop('checked', !chhhk).change();
});
Demo: Fiddle
You can check if you are clicking the checkbox before changing.
$('.check-unit').on('click', function (e) {
if (!($(e.target).hasClass('check'))) {
var checkbox = $(this).children('.check'),
chhhk = checkbox.prop('checked');
checkbox.prop('checked', !chhhk).change();
}
});
Also note that the code is using prop instead of attr because when you are using boolean attribute values you should use .prop()
DEMO

jquery .find() not working

This code should clear the checkboxes when I click the button. It works if I remove the <form></form> tags, but I thought .find() was supposed to find all descendants?
<script type="text/javascript">
$(document).ready(function(){
var clearCheckboxes = function() {
$('.outerbox').find('input').each(function() {
$(this).attr('checked', false);
});
}
$('input.myButton').click(clearCheckboxes);
});
</script>
<div class="outerbox">
<form>
<input type="checkbox" checked="" /> checkbox1
<input type="checkbox" checked="" /> checkbox2
</form>
</div>
<input class="myButton" value="clear checkboxes now" type="button"/>
This code works fine for me: http://jsfiddle.net/CgsEu/
Anyway, if you are using the latest jQuery, try changing .attr to .prop. Also the .each isn't needed. .attr and .prop work on all elements in a jQuery object.
var clearCheckboxes = function() {
$('.outerbox').find('input').prop('checked', false)
}
DEMO: http://jsfiddle.net/CgsEu/1/
If there are other inputs, try limiting the .find to just checkboxes.
var clearCheckboxes = function() {
$('.outerbox').find('input:checkbox').prop('checked', false)
}
DEMO: http://jsfiddle.net/CgsEu/2/
$(document).ready(function(){
var clearCheckboxes = function() {
$('.outerbox').find('input[type="checkbox"]').each(function(){
$(this).prop('checked', false);
});
}
$('input.myButton').click(clearCheckboxes);
});​
DEMO.
Update:
$('.outerbox').find('input[type="checkbox"]').prop('checked', false);
or
$('.outerbox input:checkbox').prop('checked', false);
DEMO.
There's no need to use each(), you already have a collection of the elements and can apply the change to all of them, like so:
var clearCheckboxes = function() {
$('input', '.outerbox').attr('checked', false);
}
$('input.myButton').click(clearCheckboxes);
FIDDLE
There are a lot of suggestions to use prop() over attr(), and that is probably sound advice.
According to the W3C forms specification, the checked attribute is a
boolean attribute, which means the corresponding property is true if
the attribute is present at all—even if, for example, the attribute
has no value or an empty string value. The preferred
cross-browser-compatible way to determine if a checkbox is checked is
to check for a "truthy" value on the element's property using one of
the following:
if ( elem.checked )
if ( $(elem).prop("checked") )
if ( $(elem).is(":checked") )
To maintain backwards compatability, the .attr() method in
jQuery 1.6.1+ will retrieve and update the property for you so no code
for boolean attributes is required to be changed to .prop().
Nevertheless, the preferred way to retrieve a checked value is prop().
Use prop, e.g.
$(this).prop('checked', false);
instead if attr
var clearCheckboxes = function() {
$('input[type="checkbox"]', '.outerbox').prop('checked', false);
}
$('input.myButton').click(clearCheckboxes);

toggle checkbox attribute with jquery [duplicate]

I've used a hover function where you do x on mouseover and y and mouseout. I'm trying the same for click but it doesn't seem to work:
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', true );
},function(){
$(this).find(':checkbox').attr('checked', false );
});
I want the checkbox to be checked when clicking on a div, and unchecked if clicked again - a click toggle.
This is easily done by flipping the current 'checked' state of the checkbox upon each click. Examples:
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox.attr('checked'));
});
or:
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox.is(':checked'));
});
or, by directly manipulating the DOM 'checked' property (i.e. not using attr() to fetch the current state of the clicked checkbox):
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox[0].checked);
});
...and so on.
Note: since jQuery 1.6, checkboxes should be set using prop not attr:
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.prop('checked', !$checkbox[0].checked);
});
Another approach would be to extended jquery like this:
$.fn.toggleCheckbox = function() {
this.attr('checked', !this.attr('checked'));
}
Then call:
$('.offer').find(':checkbox').toggleCheckbox();
Warning: using attr() or prop() to change the state of a checkbox does not fire the change event in most browsers I've tested with. The checked state will change but no event bubbling. You must trigger the change event manually after setting the checked attribute. I had some other event handlers monitoring the state of checkboxes and they would work fine with direct user clicks. However, setting the checked state programmatically fails to consistently trigger the change event.
jQuery 1.6
$('.offer').bind('click', function(){
var $checkbox = $(this).find(':checkbox');
$checkbox[0].checked = !$checkbox[0].checked;
$checkbox.trigger('change'); //<- Works in IE6 - IE9, Chrome, Firefox
});
You could use the toggle function:
$('.offer').toggle(function() {
$(this).find(':checkbox').attr('checked', true);
}, function() {
$(this).find(':checkbox').attr('checked', false);
});
Why not in one line?
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', !$(this).find(':checkbox').attr('checked'));
});
I have a single checkbox named chkDueDate and an HTML object with a click event as follows:
$('#chkDueDate').attr('checked', !$('#chkDueDate').is(':checked'));
Clicking the HTML object (in this case a <span>) toggles the checked property of the checkbox.
jQuery: Best Way, delegate the actions to jQuery (jQuery = jQuery).
$( "input[type='checkbox']" ).prop( "checked", function( i, val ) {
return !val;
});
try changing this:
$(this).find(':checkbox').attr('checked', true );
to this:
$(this).find(':checkbox').attr('checked', 'checked');
Not 100% sure if that will do it, but I seem to recall having a similar problem. Good luck!
$('.offer').click(function(){
if ($(this).find(':checkbox').is(':checked'))
{
$(this).find(':checkbox').attr('checked', false);
}else{
$(this).find(':checkbox').attr('checked', true);
}
});
In JQuery I don't think that click() accepts two functions for toggling. You should use the toggle() function for that: http://docs.jquery.com/Events/toggle
$('.offer').click(function() {
$(':checkbox', this).each(function() {
this.checked = !this.checked;
});
});
Easiest solution
$('.offer').click(function(){
var cc = $(this).attr('checked') == undefined ? false : true;
$(this).find(':checkbox').attr('checked',cc);
});
<label>
<input
type="checkbox"
onclick="$('input[type=checkbox]').attr('checked', $(this).is(':checked'));"
/>
Check all
</label>
Another alternative solution to toggle checkbox value:
<div id="parent">
<img src="" class="avatar" />
<input type="checkbox" name="" />
</div>
$("img.avatar").click(function(){
var op = !$(this).parent().find(':checkbox').attr('checked');
$(this).parent().find(':checkbox').attr('checked', op);
});
$('controlCheckBox').click(function(){
var temp = $(this).prop('checked');
$('controlledCheckBoxes').prop('checked', temp);
});

jquery select all checkboxes

I have a series of checkboxes that are loaded 100 at a time via ajax.
I need this jquery to allow me to have a button when pushed check all on screen. If more are loaded, and the button is pressed, to perhaps toggle all off, then pressed again toggle all back on.
This is what i have, obviously its not working for me.
$(function () {
$('#selectall').click(function () {
$('#friendslist').find(':checkbox').attr('checked', this.checked);
});
});
The button is #selectall, the check boxes are class .tf, and they all reside in a parent div called #check, inside a div called #friend, inside a div called #friendslist
Example:
<div id='friendslist'>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr1'>
</div>
</div>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr2'>
</div>
</div>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr3'>
</div>
</div>
</div>
<input type='button' id='selectall' value="Select All">
I know I'm revisiting an old thread, but this page shows up as one of the top results in Google when this question is asked. I am revisiting this because in jQuery 1.6 and above, prop() should be used for "checked" status instead of attr() with true or false being passed. More info here.
For example, Henrick's code should now be:
$(function () {
$('#selectall').toggle(
function() {
$('#friendslist .tf').prop('checked', true);
},
function() {
$('#friendslist .tf').prop('checked', false);
}
);
});
$('#friendslist .tf')
this selector will suit your needs
Use the jquery toggle function. Then you can also perform whatever other changes you may want to do along with those changes... such as changing the value of the button to say "check all" or "uncheck all".
$(function () {
$('#selectall').toggle(
function() {
$('#friendslist .tf').attr('checked', 'checked');
},
function() {
$('#friendslist .tf').attr('checked', '');
}
);
});
A very simple check/uncheck all without the need of loop
<input type="checkbox" id="checkAll" /> Check / Uncheck All
<input type="checkbox" class="chk" value="option1" /> Option 1
<input type="checkbox" class="chk" value="option2" /> Option 2
<input type="checkbox" class="chk" value="option3" /> Option 3
And the javascript (jQuery) accounting for "undefined" on checkbox value
** UPDATE - using .prop() **
$("#checkAll").change(function(){
var status = $(this).is(":checked") ? true : false;
$(".chk").prop("checked",status);
});
** Previous Suggestion - may not work **
$("#checkAll").change(function(){
var status = $(this).attr("checked") ? "checked" : false;
$(".chk").attr("checked",status);
});
OR with the suggestion from the next post using .prop() combined into a single line
$("#checkAll").change(function(){
$(".chk").attr("checked",$(this).prop("checked"));
});
This is how I toggle checkboxes
$(document).ready(function() {
$('#Togglebutton').click(function() {
$('.checkBoxes').each(function() {
$(this).attr('checked',!$(this).attr('checked'));
});
});
});
maybe try this:
$(function () {
$('#selectall').click(function () {
$('#friendslist .tf').attr('checked', this.checked);
});
});
<div class="control-group">
<input type="checkbox" class="selAllChksInGroup"> All
<input type="checkbox" value="NE"> Nebraska
<input type="checkbox" value="FL"> Florida
</div>
$(document).ready(function(){
$("input[type=checkbox].selAllChksInGroup").on("click.chkAll", function( event ){
$(this).parents('.control-group:eq(0)').find(':checkbox').prop('checked', this.checked);
});
});
I could not get this last example to work for me. The correct way to query the state of the checkbox is apparently :
var status = $(this).prop("checked");
and not
var status = $(this).attr("checked") ? "checked" : false;
as above.
See jQuery receiving checkbox status
It works for me (IE, Safari, Firefox) by just changing your this.checked to 'checked'.
$(function() {
$('#selectall').click(function() {
$('#friendslist').find(':checkbox').attr('checked', 'checked');
});
});
You may try this:
$(function () {
$('#selectall').click(function () {
$('#friendslist input:checkbox').attr('checked', checked_status);
});
});
//checked_status=true/false -as the case may be, or set it via a variable
assuming #selectall is a checkbox itself whose state you want copied to all the other checkboxes?
$(function () {
$('#selectall').click(function () {
$('#friendslist input:checkbox').attr('checked', $(this).attr('checked'));
});
});
try this
var checkAll = function(){
var check_all = arguments[0];
var child_class = arguments[1];
if(arguments.length>2){
var uncheck_all = arguments[2];
$('#'+check_all).click(function (){
$('.'+child_class).attr('checked', true);
});
$('#'+uncheck_all).click(function (){
$('.'+child_class).attr('checked', false);
});
$('.'+child_class).click(function (){
var checkall_checked = true;
$('.'+child_class).each(function(){
if($(this).attr('checked')!=true){
checkall_checked = false;
}
});
if(checkall_checked == true){
$('#'+check_all).attr('checked', true);
$('#'+uncheck_all).attr('checked', false);
}else{
$('#'+check_all).attr('checked', false);
$('#'+uncheck_all).attr('checked', true);
}
});
}else{
$('#'+check_all).click(function (){
$('.'+child_class).attr('checked', $(this).attr('checked'));
});
$('.'+child_class).click(function (){
var checkall_checked = true;
$('.'+child_class).each(function(){
if($(this).attr('checked')!=true){
checkall_checked = false;
}
});
$('#'+check_all).attr('checked', checkall_checked);
});
}
};
To "check all" and "uncheck all" is same checkbox
checkAll("checkall_id", "child_checkboxes_class_name");
To "check all" and "uncheck all" is separate checkbox
checkAll("checkall_id", "child_checkboxes_class_name", "uncheckall_id");
Here is how I achieved it.
function SelectAllCheckBoxes();
{
$('#divSrchResults').find(':checkbox').attr('checked', $('#chkPrint').is(":checked"));
}
The following fires the above line.
<input type=checkbox id=chkPrint onclick='SelectAllCheckBoxes();' />
On the click of chkPrint , every checkbox in the grid divSrchResults' is either checked or unchecked depending on the status of chkPrint.
Of course, if you need advanced functions like unchecking the titled checkbox when every other checkbox has been unchecked, you need to write another function for this.
I created a function that I use on all projects. This is just the initial draft, but maybe it will help:
Function:
function selectAll(wrapperAll, wrapperInputs) {
var selectAll = wrapperAll.find('input');
var allInputs = wrapperInputs.find('input');
console.log('Checked inputs = ' + allInputs.filter(':not(:checked)').length);
function checkitems(allInputs) {
//If all items checked
if (allInputs.filter(':not(:checked)').length === 0) {
console.log('Function: checkItems: All items checked');
selectAll.attr('checked', true);
} else {
console.log('Function: checkItems: Else all items checked');
selectAll.attr('checked', false);
}
}
checkitems(allInputs);
allInputs.on('change', function () {
checkitems(allInputs)
});
selectAll.on('change', function () {
if (this.checked) {
console.log('This checkbox is checked');
wrapperInputs.find(':checkbox').attr('checked', true);
} else {
console.log('This checkbox is NOT checked');
wrapperInputs.find(':checkbox').attr('checked', false);
}
});
}
It accepts the 2 parameters where the inputs are wrapped into and you cand use-it like this:
$(function () {
var wrapperAll = $('.selectallinput');
var wrapperInputs = $('.inputs');
selectAll(wrapperAll, wrapperInputs);
});
See demo: http://jsfiddle.net/cHD9z/
So "checked" is a crappy attribute; in many browsers it doesn't work as expected :-( Try doing:
$('#friendslist').find(':checkbox')
.attr('checked', this.checked)
.attr('defaultChecked', this.checked);
I know setting "defaultChecked" doesn't make any sense, but try it and see if it helps.
<input type="checkbox" onclick="toggleChecked(this.checked)"> Select / Deselect All
Now here are two versions of the toggleChecked function dependent on the semantics of your document. The only real difference is the jQuery selector for your list checkboxes:
1: All checkboxes have a class of “checkbox” (<input type=”checkbox” class=”checkbox” />)
function toggleChecked(status) {
$(".checkbox").each( function() {
$(this).attr("checked",status);
})
}
2: All the checkboxes are contained within a div with an arbitary id:
<div id="checkboxes">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
In this case the function would look like this:
function toggleChecked(status) {
$("#checkboxes input").each( function() {
$(this).attr("checked",status);
})
Have fun!
This may work for both (checked/unchecked) selectall situations:
$(document).ready(function(){
$('#selectall').click(function () {
$("#friendslist .tf").attr("checked",function(){return $(this).attr("checked") ? false : true;});
});
});
The currently accepted answer won't work for jQuery 1.9+. The event handling aspect of the (rather heavily) overloaded .toggle() function was removed in that version, which means that attempting to call .toggle(function, function) will instead just toggle the display state of your element.
I'd suggest doing something like this instead:
$(function() {
var selectAll = $('#selectall');
selectAll.on('click', function(e) {
var checked = !(selectAll.data('checked') || false);
$('#friendslist .tf').prop('checked', checked);
selectAll.data('checked', checked);
});
});
That uses a regular click event handler, plus a data attribute to track the "toggled" status and invert it with each click.
Here's a basic jQuery plugin I wrote that selects all checkboxes on the page, except the checkbox/element that is to be used as the toggle. This, of course, could be amended to suit your needs:
(function($) {
// Checkbox toggle function for selecting all checkboxes on the page
$.fn.toggleCheckboxes = function() {
// Get all checkbox elements
checkboxes = $(':checkbox').not(this);
// Check if the checkboxes are checked/unchecked and if so uncheck/check them
if(this.is(':checked')) {
checkboxes.prop('checked', true);
} else {
checkboxes.prop('checked', false);
}
}
}(jQuery));
Then simply call the function on your checkbox or button element:
// Check all checkboxes
$('.check-all').change(function() {
$(this).toggleCheckboxes();
});
As you are adding and removing more checkboxes via AJAX, you may want to use this instead of .change():
// Check all checkboxes
$(document).on('change', '.check-all', function() {
$(this).toggleCheckboxes();
});

Categories

Resources