How to use a javascript variable within an html td id - javascript

In order to check cells in my table for whether they contain a value in javascript, it seems I need to give each td an id. I'll have thousands of cells, so typing out each td with its id isn't possible.
Currently the trs with all the tds are generated with a loop in html, so with javascript I wanted to add a variable and stick it on the end of each id.
I've managed to get a javascript variable into my html loop and it's correctly counting up, but my issue is getting it into the id="___" part.
As shown in the code below, I've tried putting the document.write(i) line into the id, but it seems to treat it just as normal text. I've also put it in the output for DataEntryStatus just to prove that it's counting correctly, starting at 1 and increasing with each new row.
<table class="table" id="table_id">
<tr>
<th style="color:#ddd">fffffffffffffff<br>f<br>f<br>f</th>
<th style="vertical-align:bottom;">Data Entry Status</th>
<th style="vertical-align:bottom;">Tool</th>
</tr>
<tbody id="myTable">
<script>
var i = 1;
</script>
{% for item in items %}
<tr>
<td>
Edit
! X !
</td>
<td id="DataEntryStatus"><div>{{ item.DataEntryStatus }} <script>document.write(i)</script></div></td>
<td id="Tool + <script>document.write(i)</script>"><div>{{ item.Tool }}</div></td>
</tr>
<script>
i = i + 1;
</script>
{% endfor %}
</tbody>
And my javascript:
$('#table_id tr').each(function(){
if($('#Tool' + 'i').text() =="")$('#DataEntryStatus' + 'i').text("Entry missing");
else if($('#CutRef' + 'i').text() =="")$('#DataEntryStatus' + 'i').text("Entry missing");
else($('#DataEntryStatus' + 'i').text("Complete"));
if($(this).text().toLowerCase() =="entry missing")$("#DataEntryStatus").css('background-color','#fcc');
if($(this).text().toLowerCase() =="complete")$("#DataEntryStatus").css('background-color','#af0');
});
I want something like my id="Tool + document.write(i)" line to make ids like Tool1, Tool2, ... but right now it's treating + document.write(i) as normal text and I don't know how to get it to work as a script.

It looks like you're using Django, so why not just add the ID using that?
<table class="table" id="table_id">
<tr>
<th style="color:#ddd">fffffffffffffff<br>f<br>f<br>f</th>
<th style="vertical-align:bottom;">Data Entry Status</th>
<th style="vertical-align:bottom;">Tool</th>
</tr>
<tbody id="myTable">
{% for item in items %}
<tr>
<td>
Edit
! X !
</td>
<td id="DataEntryStatus{{ forloop.counter0 }}"><div>{{ item.DataEntryStatus }}</div></td>
<td id="Tool{{ forloop.counter0 }}"><div>{{ item.Tool }}</div></td>
</tr>
{% endfor %}
</tbody>
Django has a forloop variable inside loops that gives you access to the current index.
Update
To use that with JavaScript, change counter to counter0. This is now the same as an index within a JavaScript loop.
You'd access that by looping through with .each as you have been, but with a slight modification.
$('#table_id tr').each(function(i){
if($('#Tool' + i).text() =="")$('#DataEntryStatus' + i).text("Entry missing");
else if($('#CutRef' + i).text() =="")$('#DataEntryStatus' + i).text("Entry missing");
else($('#DataEntryStatus' + i).text("Complete"));
if($(this).text().toLowerCase() =="entry missing")$("#DataEntryStatus").css('background-color','#fcc');
if($(this).text().toLowerCase() =="complete")$("#DataEntryStatus").css('background-color','#af0');
});

Related

How to sum up Total Income and Total Indirect Income Using Jquery

I want to sum up total income and total indirect income. This total values in html table comes using jQuery by providing a class. But now I want to sum up two table total values in a single variable and put in a new html table.
The new html table looks like we have a column total (income+indirect income) = variable. Click to see the HTML table
How can I do that using jQuery. Click this link and see that the values of total amount column are sum up and lies in the footer on every table. But now I want to sum up two table values in a single variable and that new variable I want to put in a new html table on a same page.
$(document).ready(function() {
var total_1 = 0;
$('.income-amount').each(function(i, obj) {
total_1 += parseInt($(obj).text());
});
$('#income-total').text(total_1.toFixed(1));
});
I use this jQuery in the Html table for total amount column sum up.
Below is the html table.
<table id="example" class="table table-striped table-bordered table-responsive-xl">
<caption style="caption-side:top; text-align: center;"><h3>Income</h3></caption>
<thead class="thead-dark">
<tr>
{# <th>S No.</th>#}
<th>Particulars</th>
<th>Description</th>
<th>Total Amount</th>
</tr>
</thead>
<tbody>
{% for item in all_profit %}
{% if item.category.under == "Income" %}
<tr>
{# <td>{{ }} </td>#}
<td>{{item.category}}</td>
<td>{{item.category.desc}}</td>
<td class='income-amount'>{{ item.balance }} </td>
</tr>
{% endif %}
{% endfor %}
</tbody>
<tfoot>
<tr class="totalColumn">
<td style="visibility:hidden;"></td>
<td style="visibility:hidden;"></td>
<td id='income-total'>Total:</td>
</tr>
</tfoot>
</table>

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" />

Adding value from th tag and set total in the final column javascript

I have values from my database and in my view I have added one column
added for the total or average value.In every rows, it has 3 columns
with values.In database there is no column for average yet instead of
putting in database, I only put in my blade.php. How could i possibly
do it in javascript?It seems like i don't know what to start since I'm
not a master in java.
<tbody>
#foreach($card['AllGrade'] as $subject)
<tr>
<th colspan="4">{!! $subject['subject'] !!}</th>
<th colspan="2" >{!! $subject['term_1'] !!}</th>
<th colspan="2" >{!! $subject['term_2'] !!}</th>
<th colspan="2" >{!! $subject['term_3'] !!}</th>
<th colspan="2" name ="ave" id ="ave" value=""> total value here</th>
</tr>
#endforeach
I think you should not code like this, You can use php code to add/average the result.Because you are expecting you can check the code given here. Just add this code to your blade file and of-course use Jquery
$("tbody tr").each(function() {
var total = 0;
$(this).children('th').not(':first').not(':last').each(function () {
//"this" is the current element in the loop
var number = parseInt($(this).html());
total += number;
});
$(this).children('th').last().html(total);
});

How do I get the total sum in ng-init and ng-repeat - angularjs

Having a problem with in ng-init and ng-repeat angularjs
i'm trying to loop the fields rates to get the total
for example this is my table
nane +++++++id+++++++rate
joe +++++++++1+++++++3
joe +++++++++2+++++++3
joe +++++++++3+++++++3
joe +++++++++4+++++++3
this my code.
<table>
<tr>
<td>name</td>
<td>rate</td>
</tr>
<tr ng-repeat="item in videos">
<td>{{item.name}}</td>
<td ng-init="videos.total.rate = videos.total.rate + item.rate">{{item.rate}}</td>
</tr>
<tr>
<td>Total</td>
<td>{{videos.total.rate}}</td>
</tr>
The Result that I get is 3333 instead of 12 when added all together
this is the line with problem
<td ng-init="videos.total.rate = videos.total.rate + item.rate">{{item.rate}}</td>
if i change it to a number it works fine.
<td ng-init="videos.total.rate = videos.total.rate + 3">{{item.rate}}</td>
your help would be great.thanks
Try something like this in controller.
JS
$scope.RateTotal= 0;
for (var i = 0; i < data.length; i++) {
$scope.RateTotal= $scope.RateTotal + data[i].rate;
}
HTML
<p>{{RateTotal}}</p>
Option above is better, but if you want use ng-init use something like this.
<table ng-init="RateTotal = 0">
<thead>
<th>Rate</th>
</thead>
<tbody>
<tr ng-repeat="item in videos">
<td ng-init="$parent.RateTotal= $parent.RateTotal + item.rate">{{item.rate}}</td>
</tr>
<tr>
<thead>
<tr>
<th>Total</th>
<th>{{RateTotal}}</th>
</tr>
</thead>
</tr>
</tbody>
</table>
P.S.
This directive can be abused to add unnecessary amounts of logic into
your templates. There are only a few appropriate uses of ngInit, such
as for aliasing special properties of ngRepeat, as seen in the demo
below; and for injecting data via server side scripting. Besides these
few cases, you should use controllers rather than ngInit to initialize
values on a scope. - ngInit
move this logic into the controller. That is what it is for. The view should be displaying data.
Now you have to worry about how to cast strings to an integer and writing 4x more code in a language that angular must interpret into javascript.
The complexity you are adding here is going to be fun to maintain.
but you probably want to continue doing it wrong, in which case this should work: <table ng-init='videos.total = {"rate": 0}'>
Define a filter to calculate the total:
app.filter('calculateRateTotal',function(){
return function(input){
var total = 0;
angular.forEach(input,function(value,key){
total = total+value.rate;
});
return total;
};
});
HTML:
<td ng-bind="videos | calculateRateTotal"></td>
After 10hrs of no luck just my managed to get it right. turned to be very simple.
This is the code.
In the Controller added
$scope.getTotal = function(){
var total = 0;
for(var i = 0; i < $scope.videos.length; i++){
var item = $scope.videos[i];
total += (item.rate*1);
}
return total; }
And HTML
<table>
<tr>
<th>Rate</th>
</tr>
<tr ng-repeat="item in videos">
<td>{{item.rate}}</td>
</tr>
<tr>
<td>Total: {{ getTotal() }}</td>
</tr>
</table>
Thanks everyone for helping

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