Loop over html table and get checked checkboxes (JQuery) - javascript

I have an HTML table with a checkbox in each row.
I want to loop over the table and see if there are any checkboxes that are checked.
The following does not work:
$("#save").click( function() {
$('#mytable tr').each(function (i, row) {
var $actualrow = $(row);
checkbox = $actualrow.find('input:checked');
console.log($checkbox);
});
This prints in the console the following:
[prevObject: jQuery.fn.jQuery.init[1], context: tr, selector: "input:checked", constructor: function, init: function…]
per row regardless of whether any checkbox is checked.
Update
Same issue with:
$('#mytable tr').each(function (i, row) {
var $actualrow = $(row);
$checkbox = $actualrow.find(':checkbox:checked');
console.log($checkbox);
});

Use this instead:
$('#save').click(function () {
$('#mytable').find('input[type="checkbox"]:checked') //...
});
Let me explain you what the selector does:
input[type="checkbox"] means that this will match each <input /> with type attribute type equals to checkbox
After that: :checked will match all checked checkboxes.
You can loop over these checkboxes with:
$('#save').click(function () {
$('#mytable').find('input[type="checkbox"]:checked').each(function () {
//this is the current checkbox
});
});
Here is demo in JSFiddle.
And here is a demo which solves exactly your problem http://jsfiddle.net/DuE8K/1/.
$('#save').click(function () {
$('#mytable').find('tr').each(function () {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked') &&
row.find('textarea').val().length <= 0) {
alert('You must fill the text area!');
}
});
});

use .filter(':has(:checkbox:checked)' ie:
$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
$('#out').append(this.id);
});

The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('input[type=checkbox]').change(function () {
$('#test > tbody tr').each(function () {
if ($('input[type=checkbox]').is(':checked')) {
$('#btnexcellSelect').removeAttr('disabled');
} else {
$('#btnexcellSelect').attr('disabled', 'disabled');
}
if ($(this).is(':checked')){
console.log( $(this).attr('id'));
}else{
console.log($(this).attr('id'));
}
});
});
Here is demo in JSFiddle.

Related

Tick a checkbox in a table cell by clicking anywhere in the table cell and change background color of that cell

Basically, I have a table with each cell containing a checkbox. I want to be able to tick the checkbox by clicking anywhere within the cell and change the color of that cell which I have done.
Now the problem is that when I tick the checkbox and then untick it, that cell is not getting that cell color back, as in the when the checkbox is unticked its cell color should be back to white. Can anyone help me? Help would be highly appreciated.
Here is my fiddle http://jsfiddle.net/UcDMW/50/
$(function () {
$('table tr td').on('click', function (e) {
if (e.target.type == "checkbox") {
if ($(this).is(':checked')) {
$(this).attr('checked', false);
$(this).css('background-color', 'white');
} else {
$(this).attr('checked', true);
$(this).css('background-color', '#DFF0D8');
}
return;
} else {
if ($(this).find('input:checkbox').is(':checked')) {
$(this).css('background-color', 'white');
$(this).find('input:checkbox').attr('checked', false);
} else {
$(this).find('input:checkbox').attr('checked', true);
$(this).css('background-color', '#DFF0D8');
}
}
});
});
You can simply accomplish your task by the following snippet,
Try,
$('table tr td:has(:checkbox)').on('click', function (e) {
$(this).toggleClass('className');
if($(e.target).is(':checkbox')){ return; }
var checked = $(this).find(':checkbox')[0].checked;
$(this).find(':checkbox')[0].checked = !checked;
});
Cached version
$('table tr td:has(:checkbox)').on('click', function (e) {
$(this).toggleClass('className');
if($(e.target).is(':checkbox')) return;
var checkBox = $(this).find(':checkbox')[0];
checkBox.checked = !checkBox.checked;
});
DEMO
You could restructure like this
$('table tr td').on('click', function(e){
var checkbox = $(this).find('input:checkbox');
if (!$(e.target).is(':checkbox')) {
checkbox.prop('checked', !checkbox.is(':checked'));
}
$(this).css('background-color', checkbox.is(':checked')?'#DFF0D8':'white');
});
DEMO
You can change your js to this:
working demo
EDIT: now working also when clicking on td cells.
$(function(){
bindCells();
});
function bindCells() {
$('table tr td').on('click', function (e) {
var check = (e.target.type=="checkbox") ? e.target : $(this).find("input:checkbox").get(0);
$(check).attr('checked', !check.getAttribute('checked'));
$(this).css('background-color', (check.checked) ? '#DFF0D8' : "#FFFFFF");
});
}
alert($(this).is(':checked')); Use it and check the value. It returns false when you check or uncheck the box. This because you use isChecked on table elements(table,tr,td)
Change
if ($(this).is(':checked')) {
in line 4 to
if ($(e.target).is(':checked')) {

How to iterate over a table cells using jQuery?

I am new to jQuery and I am trying to learn it. I want to iterate over a 9 * 9 grid alerting the values of the input boxes(total 81), row wise, column wise and grid 3 * 3 wise.
Here is what I have tried:
$("#checkBox").change(function () {
if (this.checked) {
$('table tr').each(function () {
alert($(this).td.input.val());
});
$('table tr').each(function () {
alert($(this).td.input.val());
});
} else {
alert("Check Box is unchecked. AutoCheck is disabled.");
}
});
Only else alert is working. Any comment or guidance is appreciated.
This part $(this).td.input.val() of your code will raise error since jquery object does not contains a property called td.
Try,
//The following snippet would alert the text inside of each td
$('table tr td').each(function () {
alert($(this).text());
});
//The following snippet would alert the value of each input each td
$('table tr td input').each(function () {
alert($(this).val());
});
If you want to iterate row wise then try,
$('table tr').each(function () {
$(this).find('td').each(function(){
$(this).find(':input').each(function(){
alert($(this).val());
});
});
});

Check all/uncheck all - checkboxes and tabular data

I am currently using Footables to display tabular data. Each row has a checkbox. There is one master checkbox that selects all. I am running into some difficulties. The table has a filter. When I apply the filter and try to check all checkboxes within that filter it wont work. Also, since I am able to check all checkboxes at once is there away to uncheck all checkboxes? EXAMPLE
Checkbox function
$(document).on('change','input[name="check_all"]',function() {
$("input[type=checkbox]").attr('checked', true);
});
$(document).on('change','select',function() {
$('input[type=checkbox]').attr('checked', false);
});
table filter
$(function () {
$('table').footable().bind({
'footable_filtering': function (e) {
var selected = $('.filter-status').find(':selected').text();
if (selected && selected.length > 0) {
e.filter += (e.filter && e.filter.length > 0) ? ' ' + selected : selected;
e.clear = !e.filter;
}
},
'footable_filtered': function() {
var count = $('table.demo tbody tr:not(.footable-filtered)').length;
$('.row-count').html(count + ' rows found');
}
});
$('.clear-filter').click(function (e) {
e.preventDefault();
$('.filter-status').val('');
$('table.demo').trigger('footable_clear_filter');
$('.row-count').html('');
});
$('.filter-status').change(function (e) {
e.preventDefault();
$('table.demo').data('footable-filter').filter( $('#filter').val() );
});
});
use .prop() instead of .attr()
Check/uncheck only the visible rows
set the checked status to the select all checkboxes state
Try
$(document).on('change', 'input[name="check_all"]', function () {
$(".footable tr:visible input[type=checkbox]").prop('checked', this.checked);
});
try this one with not selecter which will select except the class .footable -filtered
$(document).on('change', 'input[name="check_all"]', function () {
$(".footable tr:not(.footable-filtered) input[type=checkbox]").prop('checked', this.checked);
});

Getting a table row cell value when a specific column is is clicked

I was able to retrieve all row values via table click event and getting its value via event.currentTarget.cells[4].innerText();.
But i would like to apply this if a specific column is clicked only like, when i clicked an ID 21 under Username column. It should alert all the cell values of the row. And then when I clicked the other columns it should not alert.
This is my code. Please inform me if you are having problems the way I ask.
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('#tableid').on('click', 'tr', function (event) {
alert(event.currentTarget.cells[0].innerText);
alert(event.currentTarget.cells[1].innerText);
alert(event.currentTarget.cells[2].innerText);
alert(event.currentTarget.cells[3].innerText);
alert(event.currentTarget.cells[4].innerText);
});
});
</script>
Here is my HTML http://jsfiddle.net/jE5UM/
Try
$(document).ready(function () {
$('#tableid').on('click', 'tr', function (event) {
$(this).children().each(function(){
alert($(this).text())
})
});
});
Demo: Fiddle
If you want an array as the result then
$(document).ready(function () {
$('#tableid').on('click', 'tr', function (event) {
var texts = $(this).children().map(function(){
return $.trim($(this).html())
}).get();
});
});
Demo: Fiddle
Update
$(document).ready(function () {
$('#tableid').on('click', 'tr td:nth-child(2)', function (event) {
var texts = $(this).closest('td').siblings().addBack().map(function(){
return $.trim($(this).html())
}).get();
alert(texts.join())
});
});
Demo: Fiddle
I'd suggest, in the absence of specific HTML and other information:
$(document).ready(function () {
$('#tableid').on('click', 'tr', function (event) {
var cell = event.target,
values = $(cell).siblings().addBack().map(function(){
return $(this).text();
}).get();
alert(values);
});
});
JS Fiddle demo.
References:
addBack().
get().
map().
on().
siblings().
text().

jquery - limiting toggleClass to 2 elements

<script type="text/javascript">
$(document).ready(function () {
$('#mytable td').click(function () {
$(this).toggleClass('newclass');
});
});
</script>
This function changes the class of the selected column in my table. It works fine.
However it should not allow more than 2 columns being selected at once (by selected I mean the column having the new class toggled - newclass). So it simply should not react if other columns are clicked.
How would I do this? I could count how many columns currently use newclass and if it's 2 then cancel the function. I'm not sure how to count them or if this is the best way to do it.
here's one way to ensure no more than 2
jsfiddle
$('#mytable td').click(function() {
var $this = $(this);
// toggle 'on' if
// 1. it doesn't already have the class and
// 2. and there are less than two set to .newclass
// toggle 'off' if
// 1. it already has the class and
// 2. and there are less than two set to .newclass
$this.toggleClass('newclass',
!$this.hasClass('newclass') &&
$('#mytable .newclass').length < 2);
})
The size() method shows you how many other elements match that selector, so you can test against that before applying toggleClass():
<script type="text/javascript">
$(document).ready(function () {
$('#mytable td').click(function () {
if ($("#mytable td.newclass").size() < 2)
{
$(this).toggleClass('newclass');
}
});
});
</script>
Try using the length property like this:
<script type="text/javascript">
$(document).ready(function () {
$('#mytable td').click(function () {
if ($('#mytable td.newclass').length < 2)){
$(this).toggleClass('newclass');
}
});
});
</script>
Hope this helps!
<script type="text/javascript">
$(document).ready(function () {
$('#mytable td').click(function () {
if(!$(this).hasClass('newClass')){
if($("td.newClass").size() < 2){
$(this).toggleClass('newclass');
}
}
else {
$(this).toggleClass('newclass');
}
});
});
</script>

Categories

Resources