I have a table with the below values using django.
<tr>
<td>Chips</td>
<td>2</td>
<td>20.00</td>
<td id='totalperitem'>40.00</td>
</tr>
<tr>
<td>pizza</td>
<td>2</td>
<td>100.00</td>
<td id='totalperitem'>200.00</td>
</tr>
<tr>
<td>Peanut Butter</td>
<td>2</td>
<td>50.00</td>
<td id='totalperitem'>100.00</td>
</tr>
I'm trying to get the total of the totalperitem column using the jquery 'each' function. However , i'm only getting the value of the first item.
jquery syntax:
$('#totalperitem').each(function () {
running_total += parseInt($(this).text());
console.log('sum : ' + running_total);
});
this is the output im getting in the console
sum : 40
What am i doing wrong?
Thanks,
KJ
Multiple elements with same ID are not allowed in one page.
Use class instead of id
<td class='totalperitem'>200.00</td>
And use .totalperitem as selector.
var running_total = 0;
$('.totalperitem').each(function(){
running_total += parseInt($(this).text());
console.log('sum : ' + running_total);
});
Use class instead of id and do,
var sum = $('.totalperitem').get().reduce(function(a,b){
return a + parseFloat(b.innerHTML);
},0);
Related
I'm trying to create a JavaScript to disable a row if EndDate contains a date.
The table is generate automatically so I thought to lookup how many rows the table has and start iterating through them. Check if fields in column EndDate contain a date.
If that row contains a date then disable any field in that row.
To track down the fields I used this to check if I could disable them.
document.getElementById("r0_LineItemCode").disabled = "true";
document.getElementById("r0_LineItemCode_ref_ref").disabled = "true";
document.getElementById("pr0_LineItemCode").disabled = "true";
document.getElementById("r0_ec_type").disabled = "true";
I accomplished to loop through the rows and find out how many rows there are and show the data on the console.
But now selecting that field to check if it contains a date and then disable those row items fails.
Code to track down the rows and iterate through the rows:
let text = "";
var endDateFields = [];
var rowData = document.querySelector("#RequestLinesGrid_RowIDs");
console.log(rowData);
console.log(rowData.value);
const rows = rowData.value.split(',');
rows.forEach(myFunction);
console.log(text);
console.log(r0_EndDate);
console.log(r1_EndDate);
console.log(r2_EndDate);
function myFunction(item, index) {
text += "indexNumber = " + index + " variableField: " + item + "_EndDate";
var str = item + "_EndDate";
eval(str);
console.log(str);
}
I have the feeling I'm almost there, but need a little push in the right direction :)
This is a simple logic of your problem, if date is not empty disable all inputs of the parent tr.
document.querySelector('table').querySelectorAll('td.date').forEach(el => {
if (el.innerHTML !== '') {
const parentTr = el.parentElement;
parentTr.querySelectorAll('input').forEach(input => {
input.disabled = true;
});
}
});
<table>
<thead>
<th>id</th>
<th>input1 Example</th>
<th>input2 Example</th>
<th>date Example</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td><input name='test' type='text'></td>
<td><input name='test' type='text'></td>
<td class='date'>10/10/2021</td>
</tr>
<tr>
<td>2</td>
<td><input name='test' type='text'></td>
<td><input name='test' type='text'></td>
<td class='date'>10/10/2021</td>
</tr>
<tr>
<td>1</td>
<td><input name='test' type='text'></td>
<td><input name='test' type='text'></td>
<td class='date'></td>
</tr>
</tbody>
</table>
Instead of check all row just add a simple class on td have date then check it as my example.
This question already has answers here:
How do I force jQuery append to NOT automatically close a tag?
(3 answers)
Closed 5 years ago.
I have an $.each in jquery and in this each statement I am trying to append to a table:
$.each(result, function (y, z) {
$table.append("<tr>");
$table.append("<td>" + y + "</td>");
$table.append("</tr>");
});
But I am getting weird results like so:
<tbody>
<tr></tr>
<tr></tr>
<tr></tr>
<tr></tr>
</tbody>
<td>aaa</td>
<td>bbb</td>
<td>ccc</td>
<td>ddd</td>
I am expecting
<tr>
<td>aaa</td>
<td>bbb</td>
<td>ccc</td>
<td>ddd</td>
</tr>
Please try following code, you trying to add html with append without jQuery object and secondly not appending in correct way.
$.each(result, function (y, z) {
$table.append($("<tr><td>" + y + "</td></tr>"));
});
Or,
$.each(result, function (y, z) {
var row = "<tr>"
row += "<td>" + y + "</td>";
row += "</tr>";
$table.append($(row));
});
I want to loop through a form with Javascript but my problem is that I have another form in the first form.
I'd like to loop through the first form only, not the inner one. I found this method on an other post :
var table = $("#table_cultures tbody");
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
productId = $tds.eq(0).text(),
product = $tds.eq(1).text(),
Quantity = $tds.eq(2).text();
// do something with productId, product, Quantity
alert('Row ' + (i + 1) + ':\nId: ' + productId
+ '\nProduct: ' + product
+ '\nQuantity: ' + Quantity);
});
This method works but loop through the both forms.
EDIT 1 :
The html looks like :
<form>
<table>
<tr>
<td>Something here</td>
</tr>
<tr>
<td>
<form>
<table>
//tr td ...
</table>
</form>
</td>
</tr>
</table>
</form>
nesting of <form> elements is not allowed
please see:
https://www.w3.org/TR/html5/forms.html#the-form-element
"...Flow content, but with no form element descendants..."
I have a table and for one of the <td> I want to generate the <a> tags dynamically using JavaScript.
Writing a small snippet of the code.
<table class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
#foreach (var item in list)
{
<tr>
<td>...</td>
<td>...</td>
<td> MyFunction(item.Parameter1) </td> // dynamic anchor tag
</tr>
}
</tbody>
</table>
JavaScript function.
MyFunction(Parameter1)
{
var aTag = "";
.....
..... //some formatting as per needs
aTag = '<a id="' + someId + '" alt="' + someAlt + '" title="' + someTitle + '" style ="color:Blue;text-decoration:underline;" href="#" onclick="fnAnotherFunction(' + P1 + ',' + P2 + ');">' + NameofTheTag + '</a>';
return aTag;
}
How can the string returning aTag form an <a> tag at the <tr> <td>..?
Is this possible or is their a better solution to this.
You could use .append() or .appendTo()
$('selectorForTD).append(MyFunction(item.Parameter1))`
or
var anch = MyFunction(item.Parameter1);
anch.appendTo($('selectorForTD');
I think this is what you're after.
Edit:
Since you're using jQuery, you could create your anchor element like:
MyFunction(Parameter1)
{
// var aTag = "";
.....
..... //some formatting as per needs
var aTag = $("<a>",{id:someID, alt:someAlt, title:someTitle}).css({ ...cssRules...}).click(function(e)
{
fnAnotherFunction(P1,P2);
});
return aTag;
}
Here's a quick fiddle to illustrate.
I have the current table data:
<table>
<tr class="Violão">
<td>Violão</td>
<td class="td2 8">8</td>
</tr>
<tr class="Violão">
<td>Violão</td>
<td class="td2 23">23</td>
</tr>
<tr class="Guitarra">
<td>Guitarra</td>
<td class="td2 16">16</td>
</tr>
</table>
What I want to do is groupby the TDs which are the same, and sum the values on the second td to get the total. With that in mind I´ve put the name of the product to be a class on the TR (don't know if it is needed)
and I've coded the current javascript:
$(".groupWrapper").each(function() {
var total = 0;
$(this).find(".td2").each(function() {
total += parseInt($(this).text());
});
$(this).append($("<td></td>").text('Total: ' + total));
});
by the way the current java scripr doesn't groupby.
Now i'm lost, I don't know what else I can do, or if there is a pluging that does what I want.
</tr class="Violão"> This doesn't make sense. You only close the tag: </tr>. And I'm assuming you know that since the rest of your code is proper (except for your classnames. Check this question out).
If you want to add the values of each <td> with a class of td2, see below.
Try this jQuery:
var sum = 0;
$(".td2").each(function(){
sum = sum + $(this).text();
});
This should add each number within the tds to the variable sum.
<table>
<tr class="Violão">
<td>Violão</td>
<td class="td2 8">8</td>
</tr>
<tr class="Violão">
<td>Violão</td>
<td class="td2 23">23</td>
</tr class="Violão">
<tr class="Guitarra">
<td>Guitarra</td>
<td class="td2 16">16</td>
</tr>
</table>
var dictionary = {};
$("td").each(function(){
if(!dictionary[$(this).attr("class"))
dictionary[$(this).attr("class")] = 0;
dictionary[$(this).attr("class")] += parseInt($(this).html());
});
// declare an array to hold unique class names
var dictionary = [];
// Cycle through the table rows
$("table tr").each(function() {
var thisName = $(this).attr("class");
// Add them to the array if they aren't in it.
if ($.inArray(thisName, dictionary) == -1) {
dictionary.push(thisName);
}
});
// Cycle through the array
for(var obj in dictionary) {
var className = dictionary[obj];
var total = 0;
// Cycle through all tr's with the current class, get the amount from each, add them to the total
$("table tr." + className).each(function() {
total += parseInt($(this).children(".td2").text());
});
// Append a td with the total.
$("table tr." + className).append("<td>Total: " + total + "</td>");
}
Fiddler (on the roof): http://jsfiddle.net/ABRsj/
assuming the tr only has one class given!
var sums = [];
$('.td2').each(function(){
var val = $(this).text();
var parentClass = $(this).parent().attr('class');
if(sums[parentClass] != undefined) sums[parentClass] +=parseFloat(val);
else sums[parentClass] = parseFloat(val);
});
for(var key in sums){
$('<tr><td>Total ('+key+')</td><td>'+sums[key]+'</td></tr>').appendTo($('table'));
}
I would give the table some ID and change to appendTo($('#<thID>'))
The solution:
http://jsfiddle.net/sLysV/2/
First stick and ID on the table and select that first with jQuery as matching an ID is always the most efficient.
Then all you need to do is match the class, parse the string to a number and add them up. I've created a simple example for you below
http://jsfiddle.net/Phunky/Vng7F/
But what you didn't make clear is how your expecting to get the value of the td class, if this is dynamic and can change you could make it much more versatile but hopefully this will give you a bit of understanding about where to go from here.