Deleting value in hiddenfield when checkbox is unchecked jquery - javascript

I am pretty new with jquery and javascript. But i have made this function. When a checkbox is checked, it's value get set in a hiddenfield. Here is the function.
<script>
$('#checkDk').on('change', function () {
$('#MainContent_hiddenTargetDk').val($(this).val());
console.log($("#MainContent_hiddenTargetDk").val());
});
</script>
I dont know if this is the best way of doing it, but it works. The problem is when the checkbox is unchecked the value does not get deleted from the hiddenfield. I have been searching a bit around and found this.
var value = this.checked ? this.value : "";
Can you somehow use this to check if it is checked or not? And if yes how do i incorporate it in my function?
Here is the checkbox html.
<input id="checkDk" type="checkbox" value="208" onselect="getvalue()" autocomplete="off">

This should work:
<script>
$('#checkDk').on('change', function () {
$('#MainContent_hiddenTargetDk').val( $(this).prop("checked") ? $(this).val(): "");
console.log($("#MainContent_hiddenTargetDk").val());
});
</script>

$('#checkDk').on('change', function () {
if(this.checked){
var hidden = $('<input />').attr('type', 'hidden')
.addClass('chooseNameHere')
.val($(this).val());
$('#yourFormId').append(hidden);
}else{
$('#yourFormId').find('input[name=chooseNameHere]').remove();
}
});

$("#your_checkbox").prop("checked") should return true or false indicating if the checkbox is checked or not.
Try that instead of val()

Try
<script>
$('#checkDk').on('change', function () {
if (this.checked) {
$('#MainContent_hiddenTargetDk').val($(this).val());
console.log($("#MainContent_hiddenTargetDk").val());
} else { $('#MainContent_hiddenTargetDk').val(''); }
});
</script>

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>

boolean variable in jquery

I have some issues. I have checkbox in my jsp page. So if the checkbox is checked i have to set a boolean variable to true else false. I tried something like this
<script>
$(document).ready(function() {
$(".confirmCheckbox").change(function() {
boolean confirmAssignee = false;
$(this).attr("checked") {
confirmAssignee = true;
}
alert(confirmAssignee);
});
});
But it is giving this error
SyntaxError: missing ; before statement
$(this).attr("checked") {
I have mutliple checkboxes on the page. Sample code is like this :
for loop(----)
<input type="checkbox" id="confirmBox-${loopCounter.index}" class = "confirmCheckbox">
Any help will be appreciated. Ask anything if required.
You need to use var while defining variable and use this.checked or .prop() to get whether checkbox is checked or not.
Simple statement will do it.
var confirmAssignee = this.checked; //OR $(this).prop("checked");
Complete Script
$(document).ready(function() {
$(".confirmCheckbox").change(function() {
var confirmAssignee = false;
if (this.checked) {
confirmAssignee = true;
}
alert(confirmAssignee);
});
});
There is not boolean type use var
Change
boolean confirmAssignee = false;
To
var confirmAssignee = false;
You also miss the if in the state $(this).attr("checked") { it should be if($(this).attr("checked")) {
Note use prop for checkbox instead of attr as suggest be jQuery doc.
For example, selectedIndex, tagName, nodeName, nodeType,
ownerDocument, defaultChecked, and defaultSelected should be retrieved
and set with the .prop() method. Prior to jQuery 1.6, these properties
were retrievable with the .attr() method, but this was not within the
scope of attr. These do not have corresponding attributes and are only
properties.
You can simplify code like
Live Demo
$(".confirmCheckbox").change(function () {
alert(this.checked);
});
Javascript have auto data types you didn't need to declare data types it is automatically taken in javascript. To check the checkbox using this.checked
$(".confirmCheckbox").change(function () {
var confirmAssignee = false;
if (this.checked) {
confirmAssignee = true;
}
alert(confirmAssignee);
});
Two problem in your code
one there is no boolean datatype in javascript use var instead of boolean
secondly you need to check if checkbox is checked or not in if condition
use below code:
$(document).ready(function() {
$( ".confirmCheckbox" ).change(function() {
var confirmAssignee = false;
if($(this).attr("checked")) {
}
alert(confirmAssignee);
});
});
1)use var instead of of boolean
var confirmAssignee = false;
2)use checkbox checked property
if($(this).is(':checked'))

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

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