Check whether the selected row has a checked check box - javascript

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.

Related

how to limit the checkbox checked using icheck jquery plugin?

How to limit the checkbox checked using iCheck jquery plugin. Please check wiht jsfiddle
$('input').iCheck({
checkboxClass: 'icheckbox_flat-green',
radioClass: 'iradio_flat-green',
labelHover: true,
});
});
https://jsfiddle.net/s9916jpy/2/
DEMO
Add an ifChecked event to all the checkbox with its common class i.e. .men_checkbox and check whether checked checkbox length is greater than or equal to limit which is a global variable as below:
var limit=4; //change according to your need
$(".men_checkbox").on("ifChecked",function(){
var checkboxes = $("input:checkbox");//get all the checkbox
if (checkboxes.filter(":checked").length >= limit) {
//if limit is reached disbaled all except checked and #man7
//else put an alert here instead of below lines.
checkboxes.not(":checked,#man7").iCheck('disable');
} else {
//else enable it all
checkboxes.not(":checked").iCheck('enable');
}
});
UPDATE
To display an alert you just need to prevent its default action using e.preventDefault() and display the alert. Check below code and this DEMO
$(".men_checkbox").on("ifChecked",function(e){
var checkboxes = $("input:checkbox");
var $this=$(this);
if (checkboxes.filter(":checked").length > limit) {
alert('Max limit reached');
setTimeout(function(){
$this.iCheck('uncheck');
},1);
}
});

How to show all checked values in AJAX load checkbox group

I've checkbox list that load by ajax and I want to show the checked value in page while user checking each checkbox. Please see below image.
Hear That country and City load from the ajax according to the parent selection. Here there are 4 cites are checked and I want to show those all selected city values below the check boxes.
I've used below jquery code but it doesn't work.
$("#cites input[type='checkbox']").click(function(){
var checkedc = $(this).val();
$('#show_city').html(checkedc);
});
Use .on()
You have to use Event Delegation
Syntax
$( elements ).on( events, selector, data, handler );
like this
$(document).on('change', '#cites input[type="checkbox"]',function () { //better use change event
if (this.checked) {// check if the checkbox is checked
var checkedc = this.value;
$('#show_city').html(checkedc);
}
});
or
$('parentElementPresesntAtDOMready').on('click','#cites input[type="checkbox"]',function(){
// code here
});
Updated After OP's comment
.map()
$(document).on('change', '#cites input[type="checkbox"]', function () {
var checkedc = $('#cites input[type="checkbox"]:checked').map(function () {//use map to create array of checked elements
return this.value;
}).get().join(); //than join array with comma to string
$('#show_city').html(checkedc);
});
I'm completing Tushar's answer so that you get all the checked cities :
$(document).on('change', '#cites input[type="checkbox"]',function () { //better use change event
var listChecked = "";
if (this.checked) {// check if the checkbox is checked
if (this.checked) {
var value = $(this).val();
listChecked = listChecked + value + ";";
}
}
$('#show_city').html(listChecked);
});

JQuery - Output the class name of checked checkboxes

I am wondering whether or not it is possible to output the class name of checked checkboxes each time a checkbox is checked/unchecked? For example, I have 3 checkboxes. If I check one, it'll output its class name, if I then check a 2nd one it'll output the first checkbox class name + the 2nd class name. If I then uncheck the first checkbox, it'll only output the class name of the 2nd checkbox.. and so forth? I made a JSFiddle to get started... http://jsfiddle.net/LUtJF/
Thanks
$("input[type='checkbox']").change(function() {
var classes = $("input[type='checkbox']:checked").map(function() {
return this.className;
}).get().join(",");
alert(classes);
});
Your fiddle, fiddled with.
Check this fiddle: http://jsfiddle.net/eUse5/
Code:
function showChecked() {
var s = '';
$('input:checked').each(function() {
if(s!='') s += ', ';
s += $(this).attr('class');
});
alert(s);
}
$('input[type="checkbox"]').change(showChecked);
$(document).ready(function() {
var cb = $('input[type=checkbox]');
cb.change(function() {
cb.each(function() {
if ($(this).is(':checked')) {
alert($(this).attr('class'));
}
});
});
});
It can be done like
$(":checkbox").click(function(){
var classes = "";
$(':checked[class]').each(function(){ // this will filter only checked checkbox having class attribute
classes += " "+$(this).attr("class");
});
alert(classes);
});
fiddle: http://jsfiddle.net/LUtJF/7/

How can I check if a checkbox is checked on click?

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

How to restore Textbox Data

I have a small requirement,
We have restore the textbox data that was cleared previously.
Below is my HTMl code
<table>
<tr><td><input type="textbox"></td></tr>
<tr><td><input type="checkbox"></td></tr>
</table>
Here is my JQuery Code
$('TABLE TR TD').find(':checkbox').change(function()
{
if($(this).prop('checked'))
{
$(this).parents('TR').siblings('TR').find('input').val("")
}
if(!$(this).prop('checked'))
{
$(this).parents('TR').siblings('TR').find('input').val(?)
}
});
My Requirement is to clear the textbox content if checkbox is checked. And if i deselect it the textbox should be restored with previous data.
Please someone help me.
Use a global variable to store the previous data -
var prevData;
then modify your code this way -
$('TABLE TR TD').find(':checkbox').change(function()
{
if($(this).prop('checked'))
{
var $element = $(this).parents('TR').siblings('TR').find('input')
prevData = $element.val();
$element.val("");
}
else
{
$(this).parents('TR').siblings('TR').find('input').val(prevData);
}
});
When the checkbox is being checked, before clearing the value, store it using the jQuery .data() API.
<table>
<tr><td><input type="text"></td></tr>
<tr><td><input type="checkbox"></td></tr>
</table>
$('input:checkbox').change(function() {
var input = $(this).closest('table').find('input[type="text"]');
if ($(this).prop('checked')) {
input.data('text', input.val());
input.val('');
} else {
input.val(input.data('text'));
}
});
A demo which works if there were multiple pairs, so long as they exist in separate <table> parents. You could change the finder to get the previous sibling if that were not the case. This uses no global variables which are not really best practice - How to avoid global variables in JavaScript?.
Edit: Updated demo based on your other question Keydown event is not working properly but this will only for key events and not if someone pastes text into the <input>.
I'd suggest something a little less reliant on the mark-up remaining the same (though it does require that the checkbox follows the text input):
var prevData, textInputIndex;
$('input:checkbox').change(
function(){
thisIndex = ($(this).index('table input') - 1);
textInput = $('table input').eq(thisIndex);
if ($(this).is(':checked')) {
prevData = $(textInput).eq(thisIndex).val();
$(textInput).eq(thisIndex).val('');
}
else {
$(textInput).eq(thisIndex).val(prevData);
}
});
JS Fiddle demo.
Edited to remove the problem of having only one variable to store the text-input value:
var $textInputs = $('table input:text');
var prevData, textInputIndex, affectedTextInputIndex, textInputValues = [];
$('input:checkbox').change(
function(){
affectedTextInputIndex = $(this).index('table input') - 1;
textInputIndex = $('table input').eq(affectedTextInputIndex).index('table input:text');
if ($(this).is(':checked')) {
textInputValues[textInputIndex] = $textInputs.eq(textInputIndex).val();
$textInputs.eq(textInputIndex).val('');
}
else {
$textInputs.eq(textInputIndex).val(textInputValues[textInputIndex]);
}
});
JS Fiddle demo.
Edited to remove the explicit requirement that the input elements be contained in a table:
var $textInputs = $('input:text');
var prevData, textInputIndex, affectedTextInputIndex, textInputValues = [];
$('input:checkbox').change(
function(){
affectedTextInputIndex = $(this).index('input') - 1;
textInputIndex = $('ul input').eq(affectedTextInputIndex).index('input:text');
if ($(this).is(':checked')) {
textInputValues[textInputIndex] = $textInputs.eq(textInputIndex).val();
$textInputs.eq(textInputIndex).val('');
}
else {
$textInputs.eq(textInputIndex).val(textInputValues[textInputIndex]);
}
});
JS Fiddle demo.
References:
:checkbox selector.
change().
is().
:checked selector.
index().
val().

Categories