Programmatically change checked of a checkbox - javascript

I have the following two checkboxes:
<input type="checkbox" id="id3"></input>
<input type="checkbox" id="id4"></input>
the desired behaviour is that when i click on id3, id4 should adopt.
that works fine for the first and second click but aftwerwards not anymore. any idea why?
here my script:
<script>
function test2()
{
var checked = this.checked;
if(checked)
$("#id4").attr("checked", "checked");
else
$("#id4").removeAttr("checked");
}
$("#id3").click(test2);
</script>
(or a working dojo here http://dojo.telerik.com/eviTi)

Please use prop rather than attr and it's advisable to use change event on checkbox instead of the click event.
attr does DOM manipulation but prop just changes the internal property of any DOM
<script>
function test2()
{
var checked = this.checked;
if(checked)
{
$("#id4").prop("checked", "checked");
}
else
$("#id4").prop("checked", false);
}
$("#id3").change(test2);
</script>

Use change event(not click) and play with .prop method instead of .attr
Reason: Where both a property and an attribute with the same name exists, usually updating one will update the other, but this is not the case for certain attributes of inputs, such as value and checked: for these attributes, the property always represents the current state while the attribute (except in old versions of IE) corresponds to the default value/checkedness of the input. [Ref]
function test2() {
$("#id4").prop("checked", this.checked);
}
$("#id3").change(test2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="checkbox" id="id3">
<input type="checkbox" id="id4">

Use .prop() instead of .attr()
as like this
function test2()
{
var checked = this.checked;
if(checked)
$("#id4").prop("checked", "checked");
else
$("#id4").removeAttr("checked");
}
$(document).ready(function(){
$("#id3").click(test2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="id3"></input>
<input type="checkbox" id="id4"></input>

Use .prop() instead of .attr()
function test2()
{
var checked = this.checked;
if(checked)
{
$("#id4").prop("checked", "checked");
}
else
$("#id4").removeAttr("checked");
}

I changed your code but the problem is attr(). Use prop() instead
$("body").on("change","#id3",function(){
if($(this).is(":checked")){
$("#id4").prop("checked","checked");
} else{
$("#id4").removeProp("checked");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="id3"></input>
<input type="checkbox" id="id4"></input>

You can simply use
function test2()
{
var checkBox = $("#id4");
checkBox.prop("checked", !checkBox.prop("checked"));
}
$("#id3").click(test2);

Related

Input checked attribute not working after confirm dialog cancel

I have a checkbox that when unchecked I want to confirm that the user intended to do so.
I am listening to the on.change event and use confirm() for the dialog. If the user clicks "Cancel" I have code to reset the checkbox. However, it is not obeying it. The 'checked="checked"' attribute is placed there as expected, but it does not appear as checked.
Here's a JSFiddle illustrating it:
https://jsfiddle.net/0tvzLbgk/9/
Below is the code.
$('#box').on('change', 'input', function() {
var $me = $(this);
if (this.checked) {
// Item has been checked, do nothing
}
else {
// Item has been unchecked
// Make sure it was not an accident
var confirmReset = confirm("Reset checkbox?");
if (confirmReset == true) {
// Okay, reset
}
else {
// Mistake, mark as checked again
$me.attr('checked', 'checked');
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
<input type="checkbox" />
</div>
Does anyone know why it's not following the checked attribute?
use .prop not .attr
$me.prop('checked', true);
Use prop() insead of attr() since you need to change the property here not the attribute :
$me.prop('checked', 'checked');
Hope this helps.
( Take a look to .prop() vs .attr() )
$('#box').on('change', 'input', function() {
var $me = $(this);
if (this.checked) {
// Item has been checked, do nothing
}
else {
// Item has been unchecked
// Make sure it was not an accident
var confirmReset = confirm("Reset checkbox?");
if (confirmReset == true) {
// Okay, reset
}
else {
// Mistake, mark as checked again
$me.prop('checked', 'checked');
$me.addClass('shift-input');
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
<input type="checkbox" />
</div>

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

$('input[type=checkbox]').change(function()

Currently Im have the following script which checks to see if a checkbox value has changed but its not working when I try to use it!
<script>
$('input[type=checkbox]').change(function () {
if ($(this).is(':checked')) {
if ($(this).prev().attr('checked') && $(this).val() != $(this).prev().val()) {
alert("previous checkbox has same value");
}
}
});​
</script>
<input name="" type="checkbox" value="here"/>(if this was checked)
<input name="" type="checkbox" value="here"/>(then this)
<input name="" type="checkbox" value="there"/>(would not allow prompt alert)
<input name="" type="checkbox" value="here"/>(would allow)​
you can see it working here yet it does not work when i try to use it
http://jsfiddle.net/rajaadil/LgxPn/7
The idea is to alert when a checked checkbox value is different from the previously checked checkbox value!
Currently my checkbox look like
<input type="checkbox" name="checkbox[]" onClick="getVal();setChecks(this)" value="`key`=<?php echo $rspatient['key']?>" class="chk" id="chk<?php echo $a++?>"/>
I thought the function ('input[type=checkbox]').change(function() would get these but im wrong somewhere?
To select the previous checked sibling checkbox, use this:
$(this).prevAll(":checked:first")
I expected to use :last, but :first is what works. This is counter-intuitive to me and inconsistent with how :first and :last usually work, but I tested it in several browsers and the result is consistent.
$(':checkbox').change(function() {
if (this.checked) {
var lastChecked = $(this).prevAll(":checked:first");
if (this.value == lastChecked.val()) {
alert("previous checked box has same value");
}
}
});
Demo: http://jsfiddle.net/LgxPn/15/
Edit: If by "previously checked checkbox" you mean the last box the user clicked, then you'll need to keep track of that yourself. There's no built-in jQuery method that will tell you anything about click history.
What happens when the user first checks several boxes, and then checks and immediately unchecks a box? Should the next most recently checked box be used? If so, then you need to keep track of all checked boxes, and what order they were clicked. Here's how you can keep track of the checked boxes:
var lastChecked = [];
$(':checkbox').change(function() {
if (this.checked) {
if (lastChecked.length && this.value == lastChecked[0].value) {
alert("the last box you checked has the same value");
}
lastChecked.unshift(this);
}
else {
lastChecked.splice(lastChecked.indexOf(this), 1);
}
});​
Demo: http://jsfiddle.net/LgxPn/21/
Just a guess (with some better syntax), try this:
<script type="text/javascript">
$(function() {
$('input:checkbox').change(function() {
if($(this).is(':checked'))
{
if ($(this).prev().prop('checked') && $(this).val() != $(this).prev().val()) {
alert("previous checkbox has same value");
}
}
});​
});
</script>
Your alert message and your if statement don't match. You check to see if the values !=, but the alert says they are equal. I'm assuming the alert is the case you want to check for. Try:
$(':checkbox').change(function() {
var $this = $(this);
var $prev = $this.prev();
if($this.is(':checked')) {
if($prev.is(':checked') && $this.val() === $prev.val()) {
alert('Previous checkbox has same value');
}
}
});​
And as the others mentioned, make sure this is all within a $(document).ready() block
This seems to work for me in Chrome:
$(function() {
$('input[type=checkbox]').click(function() {
if ($(this).is(':checked')) {
if ($(this).prev().prop('checked')) {
if ($(this).val() != $(this).prev('input[type=checkbox]').val()) {
alert("previous checkbox has same value");
}
}
}
});
});​
Here's a JSFiddle: http://jsfiddle.net/gy8EQ/

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

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