I need to trigger some code when I click a checkbox based on if a checkbox is checked or not.
But for some reason, .is(':checked') is always triggered.
This is my code.
jQuery('#selectlist input[type=checkbox]').live('click',function(){
var select_id = jQuery(this).attr('id');
if(jQuery(this).is(':checked')) {
alert('You have unchecked the checkbox');
// Remove some data from variable
} else {
alert('You have checked the checkbox');
//Add data to variable
}
}
UPDATE
I've added an example on JSFiddle: http://jsfiddle.net/HgQUS/
Use change instead of click
$(this).val();
or
$(this).prop('checked'); # on jquery >= 1.6
You will be better at searching over SO:
Get checkbox value in jQuery
How to retrieve checkboxes values in jQuery
Testing if a checkbox is checked with jQuery
this.checked
Should tell you if the checkbox is checked or not although this is just javascript so you won't be able to call it on a 'jquery' element. For example -
<input type="checkbox" id="checky">
$("#checky")[0].checked
If the input has the checked attribute, then it is obviously checked, it is removed if it is not checked.
if ($(this).attr("checked")) {
// return true
}
else {
// return false
}
However, you can adapt the above code to check if the attribute, if it is not removed and instead set to true/false, to the following:
if ($(this).attr("checked") == "true") {
// return true
}
else {
// return false
}
Additionally, I see you use jQuery as an operator for selectors, you can just use the dollar, $, symbol as that is a shortcut.
I flipped-flopped the alerts, and it works for me:
<script type="text/javascript">
jQuery('#selectlist input[type=checkbox]').live('click',function(){
var select_id = jQuery(this).attr('id');
if(jQuery(this).is(':checked')) {
alert('You have checked the checkbox');
// Remove some data from variable
} else {
alert('You have unchecked the checkbox');
//Add data to variable
}
});
</script>
Your "if" syntax is not correct.
jQuery('#selectlist_categories input[type=checkbox]').live('click',function(){
var cat_id = jQuery(this).attr('id');
// if the checkbox is not checked then alert "You have unchecked the checkbox"
if(!jQuery(this).is(':checked')) {
alert('You have unchecked the checkbox');
} else {
//else alert "You have checked the checkbox"
alert('You have checked the checkbox');
}
});
if you're confused about why it says unchecked when you check it. There is nothing wrong with your code you can just switch the unchecked and checked with each other in the alerts like this:
$('#selectlist_categories input[type=checkbox]').on('change',function(){
var cat_id = $(this).attr('id');
let cat_idText = $("input[type=checkbox]:checked").val();
if(jQuery(this).is(':checked')) {
alert('You have checked the checkbox' + " " + `${cat_idText}`);
} else {
alert('You have unchecked the checkbox');
}
});
PS: I have updated the script to work in jQuery 3.5.1 the original with the live() only works on jQuery 1.7 since it was removed in 1.9 to instead use on() and on jQuery 3.5.1 you can use $ instead of jQuery and the val() function works on all versions because it added in jQuery 1.0
Or in a nice better fashion correct the if statement as RickyCheers said adding the ! before jQuery or $ which then the if statement will turn it into a if jQuery Element is not checked
$('#selectlist_categories input[type=checkbox]').on('click',function(){
var cat_id = $(this).attr('id');
if(!jQuery(this).is(':checked')) {
alert('You have unchecked the checkbox');
} else {
alert('You have checked the checkbox');
}
});
Related
I'm using Jquery's toggle event to do some stuff when a user clicks a checkbox, like this:
$('input#myId').toggle(
function(){
//do stuff
},
function(){
//do other stuff
}
);
The problem is that the checkbox isn't being ticked when I click on the checkbox. (All the stuff I've put into the toggle event is working properly.)
I've tried the following:
$('input#myId').attr('checked', 'checked');
and
$(this).attr('checked', 'checked');
and even simply
return true;
But nothing is working. Can anyone tell me where I'm going wrong?
Edit - thanks to all who replied. Dreas' answer very nearly worked for me, except for the part that checked the attribute. This works perfectly (although it's a bit hacky)
$('input#myInput').change(function ()
{
if(!$(this).hasClass("checked"))
{
//do stuff if the checkbox isn't checked
$(this).addClass("checked");
return;
}
//do stuff if the checkbox isn't checked
$(this).removeClass('checked');
});
Thanks again to all who replied.
Use the change event instead of the toggle event, like such:
$('input#myId').change(function () {
if ($(this).attr("checked")) {
//do the stuff that you would do when 'checked'
return;
}
//Here do the stuff you want to do when 'unchecked'
});
While using the change event handler suggested by Dreas Grech is appropriate, it doesn't work well in IE 6 & 7, which doesn't fire the change event until the focus is blurred (that is, until you click outside the area of the checkbox). As QuirksMode say, "it's a serious bug".
You might want to use the click event handler, but that won't work with keyboard navigation. You need to register a keyup handler too...
See also this related question.
I haven't yet found a good cross-browser solution that supports both mouse clicks and keyboard activation of the checkboxes (and doesn't fire too many events).
Regarding your solution for checking whether the checkbox is checked or not, instead of adding your own checked class, you may use HTML's checked attribute:
$('input#myInput').change(function () {
if ($(this).attr("checked")) {
//do stuff if the checkbox is checked
} else {
//do stuff if the checkbox isn't checked
}
});
Any browser sets the checked attribute of an input element to the value "checked" if the checkbox is checked, and sets it to null (or deletes the attribute) if the checkbox is not checked.
why not using $.is() ?
$('input#myId').change(
function() {
if ($(this).is(':checked')) {
// do stuff here
} else {
// do other stuff here
}
});
This is an answer by MorningZ (I found it here) that makes totally sense:
The part you are missing is that "checkbox" is a jQuery object, not a
checkbox DOM object
so:
checkbox.checked sure would error because there is no .checked property of a jQuery
object
so:
checkbox[0].checked would work since the first item on a jQuery array is the DOM object
itself.
So in your change() function you can use
$(this)[0].checked
$('input#myId').toggle(
function(e){
e.preventDefault();
//do stuff
$(this).attr('checked', 'true');
},
function(e){
e.preventDefault();
//do other stuff
$(this).attr('checked', 'false');
}
);
this worked for me............ check it
$(":checkbox").click(function(){
if($(this).attr("id").split("chk_all")[1])
{
var ty = "sel"+$(this).attr("id").split("chk_all")[1]+"[]";
if($(this).attr("checked"))
{
$('input[name="'+ty+'"]').attr("checked", "checked");
}
else
{
$('input[name="'+ty+'"]').removeAttr("checked");
}
}
})
I did a similar approach but simply using the checked attribute such as
//toggles checkbox on/off
$("input:checkbox").change(
function(){
if(!this.checked){
this.checked=true;
}
else{
this.checked=false;
}
}
);
//end toggle
$("input[type=checkbox][checked=false]")// be shure to set to false on ready
$("input#Checkbox1").change(function() {
if ($(this).attr("checked")) {
$("#chk1").html("you just selected me")//the lable
} else {$("#chk1").html("you just un selected me") }
});
Try using a non-jquery function:
function chkboxToggle() {
if ($('input#chkbox').attr('checked'))
// do something
else
// do something else
}
then in your form:
<input id="chkbox" type="checkbox" onclick="chkboxToggle()" />
Try:
$(":checkbox").click(function(){
if($(this).attr("checked"))
{
$('input[name="name[]"]').attr("checked", "checked");
}
else
{
$('input[name="name[]"]').removeAttr("checked");
}
})
How can I check if the selected row has a column check box checked?
I can get the column innerHTML which says <input type="checkbox"> but how to check if its checked or not.
I want to see if the CB is checked?
var l_iNoOfRows=$("#imageResultsList tr").length;
for(var i=1;i<=l_iNoOfRows;i++){
var l_oSelectedRow =$("#imageResultsList tr")[i]
var l_sCbColumn =l_oSelectedRow.cells[l_iCB].innerHTML;
}
If you can get the checkbox and create a jQuery object out of it, you can use the prop method to find the value of its 'checked' property.
$yourCheckboxElement.prop('checked') will return a boolean, true if it is checked and false if it is not.
You can count checked check boxes with below codes.
var c = $(l_oSelectedRow.cells[l_iCB]).find("input[type='checkbox']:checked").length;
and detect rows had checked check box.
if (c > 0) {
// checked check box is existed.
} else {
// checked check box is now existed.
}
FIDDLE
$('.btn').click(function () {
$('#table').find("input:checkbox:checked").each(function () {
var check = $(this).closest('tr').index();
alert(check);
});
});
Iterate through all the checked checkbox and get the index of the closest tr
FIDDLE
$('.btn').click(function () {
var index =$('.input').val();
var row = $('#table').find('tr:nth-child('+index+')').find('input:checkbox')
if(row.is(':checked')){
alert(index);
}else{
alert('no check box check');
}
});
IF you want to check the row if there is a checked check get the row number use it as selector then check that row if there is a checked checkbox
A better (and easier) way to do this is like this
$("#imageResultsList tr").each(function(){
var cb = $(this).find('input [type="checkbox"]');
if(cb.prop('checked')){
alert('Checked');
} else {
alert('Not Checked');
}
});
Use jQuerys .prop function
See documentation: http://api.jquery.com/prop/
<label for="checkbox">Checkbox</label>
<input id="checkbox" type="checkbox" />
$('input[type="checkbox"]').on('click', function() {
alert($(this).prop('checked'));
});
Example:
https://jsfiddle.net/a26sw7ba/2/
In your case you could do the following with jQuery:
var l_iNoOfRows=$("#imageResultsList tr").length;
for(var i=1;i<=l_iNoOfRows;i++){
var l_oSelectedRow =$("#imageResultsList tr")[i]
var l_sCbColumn =l_oSelectedRow.cells[l_iCB].innerHTML;
alert($(l_sCbColum).prop('checked'));
}
Obviously replacing the alert with what ever statement needed to accomplish your goals.
I have a page with a list of check boxes, when a check box is checked I am updating the number of check boxes selected in side a p tag. This is all working.
The problem I have is when the user selects more than 5 checkboxes I want to use Jquery to unselect it.
This is what I have so far, the first if else works but the first part of the if doe
$("input").click(function () {
if ($("input:checked").size() > 5) {
this.attr('checked', false) // Unchecks it
}
else {
$("#numberOfSelectedOptions").html("Selected: " + $("input:checked").size());
}
});
Any ideas?
Firstly you should use the change event when dealing with checkboxes so that it caters for users who navigate via the keyboard only. Secondly, if the number of selected checkboxes is already 5 or greater you can stop the selection of the current checkbox by using preventDefault(). Try this:
$("input").change(function (e) {
var $inputs = $('input:checked');
if ($inputs.length > 5 && this.checked) {
this.checked = false;
e.preventDefault();
} else {
$("#numberOfSelectedOptions").html("Selected: " + $inputs.length);
}
});
Example fiddle
Note I restricted the fiddle to 2 selections so that it's easier to test.
You need this $(this).prop('checked', false);
You should be saying
$(this).attr('checked', false)
instead of
this.attr('checked', false)
You need this $(this).prop('checked', false);
Also this is a javascript object, if you want to use jquery you should prefer $(this).
I have a radio button selection that jquery is able to loop through them and read the values for each one just fine, but jquery can only detect when one of them has been selected. When selecting the other one, jquery just ignores it and tells me none have been selected.
jquery:
$('[name="banner_type"]').each(function() {
console.log($(this).val());
if($(this).is(':checked')) {
valid = $(this).val();
return valid;
} else if(!$(this).is(':checked')) {
valid = false;
}
});
html:
<input type="radio" id="upload" name="banner_type" value="upload" />
<input type="radio" id="html" name="banner_type" value="html" />
"upload" is being ignored by jquery, "html" is not
Im doing it this way:
valid=false;
$('[name="banner_type"]').each(function() {
if($(this).is(':checked'))
valid = $(this).val();
});
So each time You check for radio being checked, valid value is renewed.
here's fiddle for You. Function "check" checks validity, returning false if none is selected.
http://jsfiddle.net/CLaDG/
The else part is setting value for valid but not returning it. Also the value is always false for second radio button. Try this:
$('[name="banner_type"]').each(function() {
console.log($(this).val());
if($(this).is(':checked')) {
valid = $(this).val();
return valid;
} else if(!$(this).is(':checked')) {
valid = $(this).val();
return valid;
}
});
This can be written shorter and better but right now I am just fixing the issue I see.
not sure which version of jQuery you are on, but try using jQuery.prop as well as delegated event on the container might be cleaner, such as:
$('.your-radios-container').on('change','[name="banner_type"]',function(){
valid = $(this).prop('checked');
});
I have forked your fiddle to show you how it could work:
http://jsfiddle.net/AcMBR/2/
I use a jQuery function to show certain hidden text fields once you select something from a select box.
This works fine for select boxes but I can't get it to work for a checkbox.
Here is the stripped code I tried (in a nutshell) but it's not working: http://jsbin.com/uwane3/2/
Thanks for your help, I rarely use JS so my knowledge is small.
I have found 2 errors in your code:
your Checkbox has no value so you cant get more than an empty result form ".val()"
you have not bind a eventhandler to the checkbox.
http://jsbin.com/uwane3/3
$('#cf3_field_9').live('click', function(e){
if (e.target == $('#cf3_field_9')[0] && e.target.checked) {
alert('The following line could only work if the checkbox have a value.');
$.viewMapcf3_field_9[$(this).val()].show();
} else {
$.each($.viewMapcf3_field_9, function() { this.hide(); });
}
});
You have no events registered to your checkbox.
Register a click, or change handler like this:
$('#cf3_field_9').click(function(){
if ($(this).attr("checked")) {
$.viewMapcf3_field_9[$(this).val()].show();
} else {
$.each($.viewMapcf3_field_9, function() { this.hide(); });
}
});
http://api.jquery.com/category/events/