jQuery code to get checkbox length while using jQuery DataTables - javascript

I am getting wrong value while fetching the checkbox length using jQuery and jQuery DataTables.
HTML:
<table class="table table-bordered" id="dataTables-show-productList">
<thead>
<tr>
<th width="5px"><input type="checkbox" name="Select All" class="chkSelectAll" /></th>
<th>Product Information</th>
</tr>
</thead>
<tbody>
<c:forEach var="masterListVar" items="${masterList}">
<tr>
<td width="1%" align="center">
<c:if test="${masterListVar.saveFlag}">
<input type="checkbox" path="selectChecked" checked class="Projection_test" value="${masterListVar.productId}"/>
</c:if>
<c:if test="${!masterListVar.saveFlag}">
<input type="checkbox" path="selectChecked" class="Projection_test" value="${masterListVar.productId}"/>
</c:if>
</td>
<td>${masterListVar.productInfo}</td>
</tr>
</c:forEach>
</tbody>
</table>
JavaScript:
$('#dataTables-show-productList').DataTable({
width:'100%'
, responsive : true
, "bSort" : false
});
$('.chkSelectAll').click(function () {
$('.Projection_test').prop('checked', $(this).is(':checked'));
});
$('.Projection_test').click(function () {
if ($('.Projection_test:checked').length == $('.Projection_test').length) {
$('.chkSelectAll').prop('checked', true);
}
else {
$('.chkSelectAll').prop('checked', false);
}
});
$('#FavouriteList').click(function (e) {
var selectedRow = $('.Projection_test');
alert($('.Projection_test:checked').length);
e.preventDefault();
});
When paginating, while selecting only 12 values. in the alert it showing only 2 when i kept in the 2 page and testing.

CAUSE
With jQuery DataTables only visible rows exist in DOM. That is why accessing checkboxes with jQuery $() method gives you 2 nodes.
SOLUTION
To select checkboxes including those that don't exist in DOM and taking into the account current search query, use the code below:
// Select all available rows with search applied
var rows = $('#dataTables-show-productList').DataTable()
.rows({ 'search': 'applied' })
.nodes();
// Checked checkboxes
console.log($('.Projection_test:checked', rows).length);
// All checkboxes
console.log($('.Projection_test', rows).length);
You need to use this logic in all click event handlers: $('.chkSelectAll').click, $('.Projection_test').click and $('#FavouriteList').click.
NOTES
jQuery DataTables also has $() method that allows to perform a jQuery selection action on the full table. However it doesn't allow to filter out rows with search applied.
See our article jQuery DataTables – How to add a checkbox column for more information on how to work with checkboxes when using jQuery DataTables.

Related

jQuery - .each() over dynamically removed rows - numbering is off

JSFiddle: https://jsfiddle.net/dxhen3ve/4/
Hey guys,
I've been trying to figure out the issue here for some time.
Essentially, I have a table with rows. You can add new rows (works fine). However, on the deletion of rows, I would like to re-number all of the rows below it (including all of their input names/ids within).
This works fine as I have it on the first time you click "remove" for any row.. say, if you have rows 0-4 and delete row 1, you will now have rows 0-3 and they will be numbered correctly--however, after that if you click remove again on another row, the numbers do not update
The indexes are getting mixed up some how and it almost seems like it's not recognizing that I've removed an element from the DOM.. when I console.log the indexes everything looks fine.
As an example:
- Add 5 rows (0-4)
- Remove row #1 (the rows below get updated as they should).
- Remove the new row #1, and you will see that row #2 takes its place instead of changing to row #1.
- In the function 'renumber_budget_rows', the if statement seems to get skipped for that row #2, even though I feel like it should meet the conditions (and is present if I console.log(item)
What am I missing? https://jsfiddle.net/dxhen3ve/4/
** Update: Just wanted to update that I have a true resolution that works, which is great! However, I am more interested in knowing WHY my solution is failing. At the moment, the best I have, from the correct answer, was that my indexes were misaligned. I'm going to take a new look at them.
HTML
<script type="text/template" id="budget_row-template">
<tr id="budget_row-{{index}}" class="budget-row" data-budget-index="{{index}}">
<td class="budget-line">{{index}}</td>
<td><input type="text" name="budget_description-{{index}}" id="budget_description-{{index}}" class="budget-description" /></td>
<td><input type="text" name="budget_amount-{{index}}" id="budget_amount-{{index}}" class="budget-amount" /></td>
<td>
<select name="budget_costcode-{{index}}" id="budget_costcode-{{index}}" class="budget-costcode">
<option>-- Select Cost Code</option>
</select>
</td>
<td><i class="fa fa-share"></i></td>
<td>remove</td>
</tr>
</script>
<div class="table-scroll-container">
<table class="table table-striped table-bordered table-hover tablesorter" id="budget-display">
<thead>
<tr>
<th>Line #</th>
<th>Description</th>
<th>Amount</th>
<th>Cost Code</th>
<th data-sorter="false"></th>
<th data-sorter="false"></th>
</tr>
</thead>
<tbody id="test">
<tr id="budget_row-0" class="budget-row" data-budget-index="0">
<td class="budget-line">0</td>
<td><input type="text" name="budget_description-0" id="budget_description-0" class="budget-description" /></td>
<td><input type="text" name="budget_amount-0" id="budget_amount-0" class="budget-amount" /></td>
<td>
<select name="budget_costcode-0" id="budget_costcode-0" class="budget-costcode">
<option>-- Select Cost Code</option>
</select>
</td>
<td><i class="fa fa-share"></i></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div class="text-align-center">
<i class="icon icon-plus icon-white"></i> Add Line Item<br />
</div>
JS
function renumber_budget_rows(removed) {
$('#budget-display tbody .budget-row').each(function(indite, item) {
var ti = $(item).data('budget-index');
if( ti > removed ) {
ti--;
//console.log(item);
$(item).attr('id', 'budget_row-'+ti);
$(item).attr('data-budget-index', ti);
$(item).find('.budget-line').html(ti);
$(item).find('.budget-description').attr({ 'name': 'budget-description-'+ti, 'id': 'budget-description-'+ti });
$(item).find('.budget-amount').attr({ 'name': 'budget-amount-'+ti, 'id': 'budget-amount-'+ti });
$(item).find('.budget-costcode').attr({ 'name': 'budget-costcode-'+ti, 'id': 'budget-costcode-'+ti });
$(item).find('.add-budget-child').attr({ 'id': 'budget_row-addparent-'+ti, 'data-budget-index': ti });
$(item).find('.trash-budget-row').attr({ 'id': 'budget_row-'+ti+'-trash' });
$(item).find('.trash-budget-row').attr('data-budget-index', ti);
}
});
}
var budget_index = 0;
$('.add-budget-row').click(function(e) {
budget_index++;
e.preventDefault();
var budget_html = $('#budget_row-template').html();
budget_html = budget_html.replace(/{{index}}/g, budget_index);
$('#budget-display tbody').append(budget_html);
});
$('#budget-display').on('click', '.trash-budget-row', function(e) {
var removed = $(this).data('budget-index');
$(this).closest('tr').remove();
console.log(removed);
renumber_budget_rows(removed);
budget_index--;
});
While you are deleting the row, after a row deletion, you can iterate through every tr using .each() function and change the attributes based on the index i value.
$('#budget-display').on('click', '.trash-budget-row', function(e) {
var removed = $(this).data('budget-index');
$(this).closest('tr').remove();
$('tbody tr').each(function(i){
$(this).find('td').eq(0).text(i);
$(this).attr("data-budget-index",i);
$(this).attr("id","budget-row-" + i);
});
budget_index--;
});
Working example : https://jsfiddle.net/DinoMyte/dxhen3ve/5/

Select elements in each child tables one by one

I have the following html which is basically a parent table with some child tables inside it,
<table id="roottable" class="tablemain" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td></td>
<td>
<table class="intable" align="center" border="0">
<tbody>
<tr>
<td class="chn" colspan="2" align="center">
<div>
<div class="mparent">
<div class="checkbox">
<input type="checkbox" id="ch243" name="ch243" value="243">
<label for="ch243"></label>
</div>
<div class="chtext">Category</div>
</div>
</div>
</td>
</tr>
<tr>
<td>Param two</td>
<td>
<div class="checkbox">
<input type="checkbox" id="ch244" name="ch244" value="244">
<label for="ch244"></label>
</div>
</td>
</tr>
</tbody>
</table>
......
......
<table class="intable" align="center" border="0">
......
......
What I need to do is access all checkboxes of the nested table, for each table. That is get the checkboxes inside the first nested table, perform some operations with it, move to the next nested table do the same with the checkboxes inside it.
I can access individual tables like below with their id,
$('#tableid').find('input[type="checkbox"]').each(function () {
});
This works, but the tables are auto generated from db and the id is not known beforehand, also, the number of tables may vary, so I have no option other than selecting the parent table and then look for every child tables inside it one by one ... I have tried this ...
$('table').each(function(){
$(this).find('input[type="checkbox"]').each(function () {
// DO STUFFS WITH CHECKBOXES
});
But it doesn't work... How do I go about this? Thanks.
$('table tr td').each(function(){ // this line is for main outer table
$(this).children('table').each(function () { //this will iterate all the child table
$(this).find('input:checkbox').each(function(){ //this will find checkbox inside each table
//Your Stuff
});
});
});
NOTE :- I m not using id selector here because questioner mentioned that he doesn't know id's beforehand.
Working Demo
Working Demo
Your final code block looks acceptable, except that you haven't prevented the table selector from also selecting the outer table. As written, this would cause each set of checkboxes to be considered twice - once as part of its own table and again (actually first) as descendants of the outer table.
Try a more specific selector:
$('#roottable .intable').each(...)
I would do something like this:
$('#roottable').find('.intable').each(function(index, elt) {
// operate now on each "child table"
var $childTable = $(elt);
$childTable.find('input[type="checkbox"]').each(function(i, cb){
// Do your stuff with the checkoxes of the current ".intable" table
});
});
Just use:
var tableInputs = {};
$('#roottable input[type="checkbox"]').each(function () {
var id = $(this).closest('table').attr('id');
var name = $(this).attr('name');
tableInputs[id] = {};
tableInputs[id][name] = $(this).val();
});
This will select all checkboxes that are a child of a table.
EDIT if you need to group just find the id of the closest parent table and use that as an index for an object. You end up with one large object with all the id's as properties, while using only one each loop.

Can I call a jquery or javascript function in grails g:each element?

I want to call a jquery function in grails g:each element, i'm using a function call on page load to filter a table which has a loop as follows
<g:each in="${sampleTypes}" status="i" var="sampleType">
<div class="uniq">${sampleType}</div>
<table id="sampleTable">
<thead>
<tr>
<th class="no-sort"><g:message code="labWorkItem.testUnit.label"
default="CustomerId" /></th>
<th class="no-sort"><g:message code="labWorkItem.testUnit.label"
default="OrderNo" /></th>
<th class="no-sort"><g:message code="labWorkItem.testUnit.label"
default="DateCreated" /></th>
<th class="no-sort"><g:message code="labWorkItem.testUnit.label"
default="Test unit" /></th>
<th class="no-sort no-visible"><g:message
code="labWorkItem.sampleType.label" default="Sample Type" /></th>
</tr>
</thead>
<tbody>
<g:each in="${labWorkItemInstance}" status="a" var="labWorkItem">
<tr class="${(a % 2) == 0 ? 'even' : 'odd'}">
<td>
${labWorkItem?.order?.customer?.customerId}
</td>
<td>
${labWorkItem?.order?.orderNo}
</td>
<td>
${labWorkItem?.order?.dateCreated}
</td>
<td >
${labWorkItem?.testUnit}
</td>
<td id = "labSample">
${labWorkItem?.testUnit?.sampleType}
</td>
</tr>
</g:each>
</tbody>
</table>
<g:textField name="singleValue" value="Blood" id="someHiddenField"/>
</g:each>
i am using the class "uniq" to filter the table
function typeSampleCollected() {
jQuery.fn.dataTableExt.afnFiltering.push(function(oSettings, aData,
iDataIndex) {
if (oSettings.nTable.id != "sampleTable") {
return true;
}
var uniq = jQuery("div.uniq").html();
alert(uniq);
jQuery("#someHiddenField").val(uniq);
var someHiddenField = jQuery("#someHiddenField").val()
if(someHiddenField){
//var sampleValue = jQuery("#someHiddenField").val();
//alert(sampleValue.toString());
if (someHiddenField != aData[4]){
console.log("sampleType"+someHiddenField);
console.log("aData"+aData[4]);
return false;
}
}
else{
console.log("else condition");
}
return true;
});
}
The problem is, it executes at the first on page load, only the first data of the loop executed others remains the same, i want the remaining data also to execute.
jQuery + HTML answer.
Your generated HTML will be wrong because the id "someHiddenField" will be duplicated. An id has to be unique within the HTML document. View the source of the document to check. Copy into an IDE or use w3c validator to check.
Once you have unique ID's you need to iterate over them and run your filter.
I am not sure whether by filter you are sending information back to the server. i.e. text blood results in only content relating to blood being displayed. I don't see any events in your code. Is the code incomplete?
A similar thing - click on an icon to only display items relating to that class. View code:
<g:each in="${assetTypes}" status="i" var="assetType">
<li>
<span class="atext">${assetType.name?.encodeAsHTML()}</span>
</li>
</g:each>
I used delegate() to late-bind jQuery to the click - use go() after 1.7 jQuery. The javascript had to be in a grails view because I use the gsp tags. With delegate() it could be anywhere:
/* Change asset types */
jQuery('body').delegate('[name=assetTypeSelector]', 'click', function() {
var newAssetIconId = jQuery(this).attr("id").split("-").pop();
// set the asset type.
${remoteFunction(controller: 'assetType', action: 'selector', name: 'assetTypeSelector', update: 'assetTypeSelector', params:'\'currentAssetTypeIconId=\' + newAssetIconId')}
});
Alternatively we have had a lot of success with DataTables which is a more complete solution.

Get column in a row in a table if that row has a selected checkbox

I have a table like the following
<table id="adminTable">
<thead>
<tr>
<th></th>
<th>Username</th>
<th>Email</th>
<tr>
</thead>
<tbody>
<tr><td><input type='checkbox' name='selected_users[]' value='User1'/></td><td>User1</td><td>mail1#mail.com</td></tr>
<tr><td><input type='checkbox' name='selected_users[]' value='User2'/></td><td>User2</td><td>mail2#mail.com</td></tr>
...
</tbody>
</table>
I have a button below which calls a javascript-function.
This function then should get all the emails for the users which were selected via their checkboxes...
I am quite new to Javascript and jQuery an am not sure of how to achieve this...
But I can use plain Javascript or use jQuery...
What I already found was this, but I can't get it to help me, because I don't want a button in my row (multiple selections shall be possible via the checkboxes).
You can use the following function which run on a button click:
$(":button").click(function() {
var emails = $("input[name=selected_users[]]:checked").map(function() {
return $(this).closest("td").next("td").text();
}).get();
console.log(emails); //array of emails that were checked
});
$("#adminTable").find("td").filter(function()
{
return $(this).find("input[type=checkbox]:checked").length > 0;
});
Keep in mind you have TR tags in your html that don't have closing tags and are out of place.

How do I check multiple checkboxes with jquery without giving each an id?

I am trying to check multiple checkboxes using one with jQuery. I know how to do this to check all checkboxes or to check multiple if they have ids. I want to be able to do this without that though.
All of my checkboxes are in a similar grouping. I have them grouped in a consistant way.
I have my work on a fiddle here.
Here is my code
window.onCheck = function () {
var totals = [0, 0, 0];
$('tr.checkRow').each(function () {
var $row = $(this);
if ($row.children('td:first').find('input:checkbox').prop('checked')) {
$(this).find('td.imageBox').each(function (index) {
var $imageBox = $(this);
if ($imageBox.children('img:first').attr('src').indexOf('yes') >= 0) {
++(totals[index]);
}
});
}
});
$('#total1').text(totals[0]);
$('#total2').text(totals[1]);
$('#total3').text(totals[2]);
};
window.onCheckForm = function (cb) {
var $cb = $(cb);
var $table = $cb.parents("table");
$('input.subFieldCheck').find($table).prop('checked', function () { return cb.prop('checked')});
}
My problem is with the onCheckForm function.
Thank you.
Note: I started writing this answer for a duplicate of this question and realized I couldn't post this, so I posted it here instead. The table structure is different and a lot simplified in this answer.
Lets start off with a very simple table with a checkbox column:
<table>
<thead>
<tr>
<th scope='col' id='toggler'>
<input type='checkbox' id='toggleAll'>
<label for='toggleAll'>Select all</label>
</th>
<th scope='col'>A column</th>
</tr>
</thead>
<tbody>
<tr>
<td headers='toggler'>
<input type='checkbox'>
</td>
<td>some cell data</td>
</tr>
<tr>
<td headers='toggler'>
<input type='checkbox'>
</td>
<td>some cell data</td>
</tr>
<tr>
<td headers='toggler'>
<input type='checkbox'>
</td>
<td>some cell data</td>
</tr>
<tr>
<td headers='toggler'>
<input type='checkbox'>
</td>
<td>some cell data</td>
</tr>
<tr>
<td headers='toggler'>
<input type='checkbox'>
</td>
<td>some cell data</td>
</tr>
</tbody>
</table>
Here, I have a checkbox in the header along with a label for accessibility purposes (you may hide the label if you wish).
I've also given the header cell an ID and used the headers attribute for the td elements. This isn't absolutely necessary for what we're doing, however it seems like an appropriate case to use the headers attribute. If you ever want to move the checkbox to another column for certain rows, you can just add the headers attribute to that cell.
Here is some JavaScript code:
$('#toggleAll').change(function () {
$('td[headers~="toggler"] > input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});
We are binding a function to the change event to the checkbox in the header.
The selector will look for all checkboxes that are children of td elements that contain the ID toggler in a space-separated list of tokens in the headers attribute.
The .prop() method sets the checked property of the checkboxes to match the value of the checked property of the one in the header ("this").
Our basic functionality is done here.
We can make improvements though, by changing the state of the checkbox at the top to match the state of the checkboxes in the rows.
The state of the header checkbox should be:
Unchecked if 0 are checked
Interdetermine if (0, n) are checked
Checked if n are checked
Where n indicates all the checkboxes.
To do this, we bind a function to the change event of each of the boxes in the table rows:
$('td[headers~="toggler"] > input[type="checkbox"]').change(function() {
var allChecked = true, noneChecked = true;
var headerCheckbox = $('#toggleAll');
$('td[headers~="toggler"] > input[type="checkbox"]').each(function(i, domElement) {
if(domElement.checked) {
// at least one is checked
noneChecked = false;
} else {
// at least one is unchecked
allChecked = false;
}
});
if(allChecked) {
headerCheckbox.prop('checked', true);
headerCheckbox.prop('indeterminate', false);
} else if (noneChecked) {
headerCheckbox.prop('checked', false);
headerCheckbox.prop('indeterminate', false);
} else {
headerCheckbox.prop('indeterminate', true);
}
});
I'm using .each() here to loop through all of the appropriate checkboxes to determine whether all, none, or some are checked.
See the jsFiddle demo.
Hope this helps, I sure learned quite a bit while answering the question!
See this fiddle for a cleaner way:
http://jsfiddle.net/W75dy/19/
<td class="field">
<form class="fieldCheck">
<input type="checkbox" id="Row1Chk" name="Row1" value="Row1" />
</form> Programs
</td>
$('#Row1Chk').on('change', function(event) {
$('table.checkTable input[type=checkbox]').prop('checked', $(this).prop('checked'));
});

Categories

Resources