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

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/

Related

How do I filter a table by any matching code/name and not every available field

I'm trying to do the following: I have a table populated with data from the DB. Apart from that, I have an input where you can write something and a button that will filter, only showing the lines that have that string. This is working now!
The thing is, the input should only allow you to filter by foo.name/foo.code (two propertys of my entity).
I'm adding the code I have in case anyone can guide me out, I've tried several things but this are my first experiences with JQuery while I have a strict story-delivery time. Thanks everyone!
<tbody>
<c:forEach var="foo" items="${foo}">
<tr id = "fooInformation" class="mtrow">
<th id="fooName" scope="row">${foo.name}</th>
<td id="fooCode" class="left-align-text">${foo.code}</td>
<td class="left-align-text">${foo.country}</td>
<td class="left-align-text">${foo.region}</td>
<td class="left-align-text">${foo.subregion}</td>
</tr>
</c:forEach>
</tbody>
$("#search").click(function () { -> button id
var value = $("#fooRegionSearch").val(); -> value of the input
var rows = $("#fooRegionTable").find("tr"); -> table id
rows.hide();
rows.filter(":contains('" + value + "')").show();
});
To start with, your HTML is invalid - there cannot be elemenets with duplicate IDs in HTML. Use classes instead of IDs.
Then, you need to identify which TRs pass the test. .filter can accept a callback, so pass it a function which, given a TR, selects its fooName and fooCode children which contain the value using the :contains jQuery selector:
$("#search").click(function() {
var value = $("#fooRegionSearch").val();
var rows = $("#fooRegionTable").find("tr");
rows.hide();
rows.filter(
(_, row) => $(row).find('.fooName, .fooCode').filter(`:contains('${value}')`).length
).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="fooRegionTable">
<tr id="fooInformation" class="mtrow">
<th class="fooName" scope="row">name1</th>
<td class="fooCode" class="left-align-text">code1</td>
<td class="left-align-text">${foo.country}</td>
<td class="left-align-text">${foo.region}</td>
<td class="left-align-text">${foo.subregion}</td>
</tr>
<tr id="fooInformation" class="mtrow">
<th class="fooName" scope="row">name2</th>
<td class="fooCode" class="left-align-text">code2</td>
<td class="left-align-text">${foo.country}</td>
<td class="left-align-text">${foo.region}</td>
<td class="left-align-text">${foo.subregion}</td>
</tr>
</table>
<button id="search">click</button><input id="fooRegionSearch" />

how to search for a checkbox inside innerHTML?

I want to sum a selected column inside a table. 2nd and 3rd column in my case. I managed to get the sum but I really want to add the value of a row in case a checkbox in column #1 is checked.
I can get the innerHTML value of a cell abut I do not know how to search or find out if the checkbox inside is checked or not.
console.log(cell.innerHTML);
returns for example
"Extend (2x)<input type=\"checkbox\" id=\"Extend2x\" name=\"Extend2x\" class=\"beru\" <=\"\" td=\"\">
so I can see that the checkbox is there but that is where I ended up
I tried
console.log(cell.innerHTML.getElementsByTagName("checkbox"));
console.log(cell.innerHTML.html());
console.log(cell.html());
console.log($(cell).find(':checkbox').checked) returns undefined
but nothing worked.
Could somoone help me to find out? The working fiddle is here You just click the checkbox and summing of the columns will be done.
The code you are looking for is this
$(':checked')
you can add stuff like input:checked, or something to make it more specific.
EDIT--
just saw the comments - and Taplar already answered this. Well this can be considered as alternative answer, and does not need to use cells / iterate through cells of the table.
I think this is what you wanted. This is using jQuery for every reference to elements in the the dom (html).
$(".beru").on('change', function() {
updateTotals();
});
function updateTotals() {
// loop cells with class 'celkem'
$('.celkem').each(function(){
// for each celkem, get the column
const column = $(this).index();
let total = 0;
// loop trough all table rows, except the header and the row of totals
$(this).closest('table').find('tr:not(:first, :last)').each(function(){
if($(this).find('input').is(':checked')) {
// if the input is checked, add the numeric part to the total
const str = $(this).find(`td:eq(${column})`).text().replace(/\D/g, "");
if(str) {
total += Number(str);
}
}
});
if(!total) {
// if the total is zero, clear the cell
$(this).text("");
} else {
// otherwise, print the total for this column in the cell
$(this).text(total + " EUR");
}
});
}
td {
width: 25%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="Zinzino" style="border-collapse: collapse; width: 100%;" border="1">
<tbody>
<tr>
<th><strong>Název</strong></th>
<th class="sum"><strong>První balíček</strong></th>
<th class="sum"><strong>Měsíčně</strong></th>
<th> </th>
</tr>
<tr>
<td>BalanceOil <input type="checkbox" id="BalanceOil" name="BalanceOil" class="beru"></td>
<td>149 EUR</td>
<td>30 EUR</td>
<td> </td>
</tr>
<tr>
<td>Extend (2x)<input type="checkbox" id="Extend2x" name="Extend2x" class="beru"</td>
<td>44 EUR</td>
<td>22 EUR</td>
<td> </td>
</tr>
<tr>
<td>Zinobiotic (3x)<input type="checkbox" id="Zinobiotic" name="Zinobiotic" class="beru"</td>
<td>64 EUR</td>
<td>23 EUR</td>
<td> </td>
</tr>
<tr>
<td><strong>Celkem</strong></td>
<td class="celkem"> </td>
<td class="celkem"> </td>
<td> </td>
</tr>
</tbody>
</table>
If you already have a reference to the DOM element then just select all the checkboxes using a selector.
var cbList = cell.querySelectorAll("[type='checkbox']");
for(var i = 0; i < cbList.length; i++){
//do something with each checkbox
//cbList[i];
}
Remember a node list is not an array, so you can't use forEach ;)

calcul jQuery does not work

I try to change value by default with a calcul : value by default * quantity / 100. In my script something does not work because nothing happened, I can't find what! (jQuery is very new for me...)
$(function () {
$("#calcul").click(function (e) {
e.preventDefault();
var valeur = parseFloat($("#valquantite").text() );
$("#nutrition > tbody > tr").each(function () {
var valeurOrigin = parseFloat($(this).find("td").eq(1).text().replace(",", "."));
var newValeur;
if ($.isNumeric(valeurOrigin) === true) {
newValeur = valeurOrigin*valeur/100;
newValeur = Math.ceil(newValeur*1000)/1000;
} else {
newValeur = $(this).find("td").eq(1).text();
}
$(this).find("td").eq(2).html(newValeur);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="overflow-x:scroll;;" name="formu">
<table class="table table-striped" id="nutrition" >
<thead>
<tr>
<th>Aliments</th>
<th id="qty">Poids</th>
<th class="generaux">Energie kJ</th>
<th class="generaux">Energie kcal</th>
</thead>
<tbody class="text-primary" id="">
<tr><td>Pain au lait, préemballé:</td><td id="valquantite"><strong>35gr</strong></td>
<td class="generaux" name="">1510</td>
<td class="generaux">358</td>
</tr>
<tr><td>Total</td>
<td><strong>50gr</strong></td>
</tr>
</tbody>
</table>
<input class="btn btn-primary" type="button" value="Calculer" id="calcul" />
What i try to do is that the first column after the name retrieves the quantities from a table (different for each row), then I retrieve the values ​​by default columns energie_kj, energie_kcal, proteines, etc .. from a table (there are 60 Columns !! they are already calculated by default, I do not need to do any conversion). Some cells contain text (example: nc, traces, <) that I want to display as text. Then I have to calculate the total of each column (ignoring cells that contain text). That's my problem! I posted another question for the same problem with a code in js that works almost but not completely ... here: Javascript problems with NaN
Thanks in advance for your answers.
Hope this will help you. Replace your code with following : I've just parse your valeur variable and replaced > sign when calling .each function and applied Id=nutrition to table rather than tbody tag.
$(function () {
$("#calcul").click(function (e) {
e.preventDefault();
var valeur = parseInt($("#valquantite").text());
$("#nutrition tbody tr").each(function () {
var valeurOrigin = parseFloat($(this).find("td").eq(2).text().replace(",", "."));
var newValeur;
if ($.isNumeric(valeurOrigin) === true) {
newValeur = valeurOrigin*valeur/100;
newValeur = Math.ceil(newValeur*1000)/1000;
} else {
newValeur = $(this).find("td").eq(1).text();
}
$(this).find("td").eq(2).html(newValeur);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="overflow-x:scroll;;" name="formu">
<table class="table table-striped" id="nutrition">
<thead>
<tr>
<th>Aliments</th>
<th id="qty">Poids</th>
<th class="generaux">Energie kJ</th>
<th class="generaux">Energie kcal</th>
</thead>
<tbody class="text-primary">
<tr><td>Pain au lait, préemballé:</td><td id="valquantite"><strong>35gr</strong></td>
<td class="generaux" name="">1510</td>
<td class="generaux">358</td>
</tr>
<tr><td>Total</td>
<td><strong>50gr</strong></td>
</tr>
</tbody>
</table>
<input class="btn btn-primary" type="button" value="Calculer" id="calcul" />
The issue may be, we don't know exactly what it is you're trying to calculate or where the data comes from. The valQuantite to which you refer, does that change for each row? If so, why is it defined outside of the each function? If not, why does it refer to a value from the first row of the table?
Doing a little research, you seem to want to take the quantity column and use that along with the energie kJ column to calculate... something. I'd suggest using classes for the three columns, valquantite, energie-kj, and energie-kcal, which you can then use to manipulate the individual columns in a meaningful way. Using $(this).find("td").eq(2).text() is only as good as the coder -- what if the column layout changes? Instead, simply use $(this).find(".energie-kj").text() and you're good.
Now, having gotten to displaying the kj as you'd like (by taking the qty and multiplying it by the kj, then rounding), you can calculate the kCal by dividing that number by 4.1868 and rounding as you'd like.
But note, I've modified your code -- the quantity seems to change with each row, so I've moved valQuantite inside the each statement. Also, I can't stress enough, I've commented my code to the point of silliness. Doing so makes it far easier to track what each line of code is SUPPOSED to be doing, as well as what it's actually doing. And use your console, it is your debugging FRIEND! lol
$(function() {
// When the button is clicked, calculate the values.
$("#calcul").click(function(e) {
// First, make sure the button doesn't submit...
e.preventDefault();
// Each row is handled individually, so
$("#nutrition > tbody > tr").each(function() {
// First, get the qty for this row
var valeur = parseFloat($(this).find(".valquantite").text());
/****
* Here is a case. We have hard-wired to use the
* third column of the table for the original val,
* but we could also add a class for this col and
* reference that: $(this).find(".energie-kj");
****/
var valeurOrigin = parseFloat($(this).find("td").eq(2).text().replace(",", "."));
var energyKJ, energyKCal;
// If the energie kJ value is numeric, we do the first
if ($.isNumeric(valeurOrigin) === true) {
// calculate some value from the energie kJ and qty,
energyKJ = valeurOrigin * valeur / 100;
// 1 kCal = 4.1868 kJ, so do the conversion
energyKCal = (energyKJ/4.1868).toFixed(2);
energyKJ = energyKJ.toFixed(2);
} else {
// If the energie kJ value is NOT numeric, we simply
// set the displayed value to this
newValeur = $(this).find("td").eq(2).text();
}
$(this).find(".energie-kj").text(energyKJ);
$(this).find(".energie-kcal").text(energyKCal);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="overflow-x:scroll;;" name="formu">
<table class="table table-striped" id="nutrition">
<thead>
<tr>
<th>Aliments</th>
<th id="qty">Poids</th>
<th class="generaux">Energie kJ</th>
<th class="generaux">Energie kcal</th>
</thead>
<tbody class="text-primary" id="">
<tr>
<td>Pain au lait, préemballé:</td>
<td class="valquantite"><strong>35gr</strong></td>
<td class="generaux energie-kj" name="">1510</td>
<td class="generaux energie-kcal">358</td>
</tr>
<tr>
<td>Some other thing...:</td>
<td class="valquantite"><strong>45gr</strong></td>
<td class="generaux energie-kj" name="">1510</td>
<td class="generaux energie-kcal">358</td>
</tr> <tr>
<td>Total</td>
<td><strong>50gr</strong></td>
</tr>
</tbody>
</table>
<input class="btn btn-primary" type="button" value="Calculer" id="calcul" />

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.

Change background-color of 1st row in the table

Below is my table that is getting populated with spry dataset
Here is my dataset
var ds1 = new Spry.Data.XMLDataSet("/xml/data.xml", "rows/row");
Here is my jquery inside a method that is called on a button click
function addRow()
{
var newRow = new Array();
var nextID = ds1.getRowCount();
newRow['ds_RowID'] = nextID;
newRow['id'] = "x";
newRow['name'] = "Abhishek";
newRow['country'] = "India";
ds1.dataHash[newRow['ds_RowID']] = newRow;
ds1.data.push(newRow);
Spry.Data.updateRegion(ds1);
ds1.sort('name','descending');
ds1.setCurrentRow(newRow.ds_RowID);
$(".trEven td").css("background-color", "red");
alert($.fn.jquery);
/*$("#tableDg tbody tr:first").css({
"background-color": "red"
});*/
}
Here is my table
<div id="cdiv" style="width:100%;" spry:region="ds1">
<table id="tableDg"
style="border:#2F5882 1px solid;width:100%;" cellspacing="1" cellpadding="1">
<thead>
<tr id="trHead" style="color :#FFFFFF;background-color: #8EA4BB">
<th width="2%"><input id="chkbHead" type='checkbox' /></th>
<th width="10%" align="center" spry:sort="name"><b>Name</b></th>
<th width="22%" align="center" spry:sort="host"><b>Country</b></th>
</tr>
</thead>
<tbody spry:repeat="ds1">
<tr id="trOdd"
spry:if="({ds_RowNumber} % 2) != 0" onclick="ds1.setCurrentRow('{ds_RowID}');"
style="color :#2F5882;background-color: #FFFFFF" class="{ds_OddRow}">
<td><input type="checkbox" id="chkbTest" class = "chkbCsm"></input></td>
<td width="10%" align="center"> {name}</td>
<td width="22%" align="center"> {country}</td>
</tr>
<tr id="trEven"
spry:if="({ds_RowNumber} % 2) == 0" onclick="ds1.setCurrentRow('{ds_RowID}');"
style="color :#2F5882;background-color: #EDF1F5;" class="{ds_EvenRow}">
<td><input type="checkbox" class = "chkbCsm"></input></td>
<td id="tdname" width="10%" align="center"> {name}</td>
<td width="22%" align="center"> {country}</td>
</tr>
</tbody>
</table>
</div>
Am I going wrong somewhere, please guide me. Thanks :)
If I remember right, <tr> is only describing structure. <td> represents visual part of the table. Or this is how some browsers renders them.
Therefore $("#trEven td").css("background-color", "red") should work. And preferrably you should use classes instead of ids in these kind of cases where there may exist multiple instances.
Works for me (jsFiddle). What problems are you experiencing?
If your use classes instead of id's, you can use something like the following:
$('.trEven').each(function() {
$(this).css({"background-color": "red"});
});
See for reference: jQuery API - .each()
You shouldn’t be using ids for odd and even rows. id values are meant to be unique within the page.
So, I’d suggest:
<tr class="trOdd"
and:
<tr class="trEven"
and then:
$(".trEven")
If you really only want the first row in the table body to get a red background (as opposed to all the even ones), then your selector should be:
$("#tableDg tbody tr:first")

Categories

Resources