Input checked attribute not working after confirm dialog cancel - javascript

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>

Related

Unable to set checked attribute when checkbox clicked

I'm able to get all attribute of the clicked checkbox, but only cannot check it visibly.
$('body').off('click.checkbox').on('click.checkbox', '[data-checkbox]', function(event) {
var id = $(this).closest('[data-target]').attr('id');
var target = $(event.target);
if (target.is('input')) {
if(target.is(":checked") == true) {
console.debug($(this).find('input:checkbox').attr('id'));
/*
item-checkbox-1
item-checkbox-2
*/
//both below ways unable to check it
$(this).find('input:checkbox').attr('checked', 'checked');
$(this).find('input:checkbox').prop('checked', true);
//but this checks all checkboxes found which is unintended
find('input:checkbox').prop('checked', true);
} else {
//do smtg
}
} else {
selectedItem.splice($.inArray(id, selectedItem),1);
}
}
});
This is how the checkbox looks like, and its unable to check on the checkbox clicked:
HTML:
<div class="item-checkbox" data-checkbox>
<div class="checkbox">
<input type="checkbox" id="item-checkbox-2">
<label for="item-checkbox-2"></label>
</div>
</div>
You are already referencing input tags with target. So, you can directly use $(this) to check/uncheck.
So, below should work.
$(this).attr('checked', 'checked');
$(this).prop('checked', true);
try replacing input:checkbox with type selector. Like Below:
$(this).find('input[type=checkbox]').attr('checked', 'checked');

jQuery toggle checkbox and also toggle anchor text

I have a checkbox as follows:
<div class="left-col">
.......
<div class="actors-top sel-actors">
<p class="selall sel-actors"><a class="sel-actors" id=""seltext>Select all Actors</a></p>
<input type="checkbox" name="" value="" class="chk1" class="sel-actors" />
</div>
.......
</div>
I want the whole space of the div sel-actors control the checkbox checked and not checked. When Select all Actors is clicked I want all checkboxes on the left-col to be checked and the text Select all Actors to be changed into Deselect all Actors. On the click back i want it to go back to how it was.
After checking out stackoverflow i found something that checks the checkbox but doesnt toggle text with it:
$(document).ready(function() {
$(".sel-actors").click(function() {
var checkBoxes = $(".left-col input");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
});
});
I would like this to toggle text also.
Here is what you want.
$(document).ready(function() {
var SEL_ACTORS_TEXT = {
CHECKED: 'Deselect all Actors',
UNCHECKED: 'Select all Actors'
};
$(".sel-actors").click(function() {
var checkBoxes = $(".left-col input"),
$this = $(this);
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
if ($this.prop('checked')) {
$this.text(SEL_ACTORS_TEXT.CHECKED);
} else {
$this.text(SEL_ACTORS_TEXT.UNCHECKED);
}
});
});
Basically, add a variable to store the potential text strings and then after updating the checkboxes, set the string accordingly.
Hope this helps!
Try this:
$('.sel-actors').text('Deselect all Actors');
EDIT: to incorporate it into your function, do this:
$(document).ready(function() {
$(".sel-actors").click(function() {
var checkBoxes = $(".left-col input");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
if($('chk1').is(':checked'))
$(this).text('Deselect all Actors');
else
$(this).text('Select all Actors');
});
});
EDIT #2: note that you have defined the class property twice for your checkbox; try either merging them or maybe setup chk1 as an id instead, then you'd call it like this: $('#chk1'). You may also want to add an id for your anchor holding the text to differentiate it from the checkbox; modify the function accordingly, of course.
EDIT #3: Here is the cleaned up code:
$(document).ready(function() {
$("#chk1").click(function() {
var checkBoxes = $(".left-col input");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
if($(this).is(':checked'))
$('#seltext').text('Deselect all Actors');
else
$('#seltext').text('Select all Actors');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="sel-actors" id="seltext">Select all Actors</a>
<input type="checkbox" name="" value="" id="chk1" class="sel-actors" />
Try the following.
<script type="text/javascript">
$('.sel-actors').click(function (event) {
if (this.checked) {
$('.chk1').each(function () {
$('.sel-actors').val("De-select all Actors");
this.checked = true;
});
} else {
$('.chk1').each(function () {
$('.sel-actors').val("Select all Actors");
this.checked = false;
});
}
});
</script>

hide div when no checkbox is checked

I am trying to show hidden text if at least one checkbox is checked and hide it if none are checked. I have a multiple checkboxes.The hidden text isn't showing when I check the checkooxes. Any help?
Here is fiddle http://jsfiddle.net/HDGJ9/1/
<input type="checkbox" name="ch[]">
<input type="checkbox" name="ch[]">
<input type="checkbox" name="ch[]">
<input type="checkbox" name="ch[]">
<div class="txt" style="display:none">
if($('input[name="ch[]"]').is(':checked'))
$(".txt").show(); // checked
else
$(".txt").hide(); // unchecked
Enclose/wrap your code with event handler like
$('input[name="ch[]"]').on('change', function () {
//your code
});
JSFiddle
You can just check the length of checked checkboxes...
var $checkboxes = $(':checkbox');
$checkboxes.on('change', function(){
$('.txt').toggle( $checkboxes.filter(':checked').length > 0 );
});
Nothing is executing your javascript code. There are many ways to execute, and also many ways to achieve the result you want. You can assign it to a click or change event like so:
$("input[name='ch[]']").click(function() {
if($('input[name="ch[]"]').is(':checked'))
$(".txt").show(); // checked
else
$(".txt").hide(); // unchecked
});
Here is an updated fiddle that checks your function everytime you click.
In your code, the test for checked/unchecked boxes occurs only once, when the page loads. You should run this check every time the value of any of the checkboxes changes. Something like
function refresh() {
if ($('input[name="ch[]"]').is(':checked')) {
$(".txt").show(); // checked
} else {
$(".txt").hide(); // unchecked
}
}
$('input:checkbox').change(refresh);
JSFiddle: http://jsfiddle.net/MHB8q/1/
You are selecting all four checkbox elements here, you need to only select one that is checked, and see if you get a result:
if($('input[name="ch[]"]').filter(':checked').length){
$(".txt").show(); // checked
} else {
$(".txt").hide(); // unchecked
}
Demo: http://jsfiddle.net/HDGJ9/10/
$('input[name="ch[]"]').on('change', function() {
if ($(this).is(':checked')) {
$('.txt').css('display', 'block');
}
else {
var checked = false;
$('input[name="ch[]"]').each(function(i, el) {
if ($(el).is(':checked')) checked = true;
});
if (!checked) $('.txt').css('display', 'none');
}
});
Version with the least amount of event handlers:
$(document).on("change", ":checkbox", function(){
var isAtLeastOneCheckboxChecked = $(':checkbox').filter(":checked").length > 0;
if (isAtLeastOneCheckboxChecked)
$('.txt').show();
else
$('.txt').hide();
});
Fiddle: http://jsfiddle.net/3d79N/

$('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 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