How can I dynamically add table rows [duplicate] - javascript

This question already has answers here:
Adding a table row in jQuery
(42 answers)
Closed 9 years ago.
I'm using foundation 5 framework (not sure if that matters). I will be passing all information to another page, so it's very important that each CELL is an individual distinguishable item/value when I do pass it, but I'm not sure on how to start on this problem. It should add another row every time add is hit. Same goes for Delete.
Can anyone guide me on how to approach this? Here is what my mark up looks:
<a href="#" class="button>Add line</a>
<a href="#" class="button>Delete line</a>
<div style="width:98%; margin:0 auto">
<table align="center">
<thead>
<tr>
<th>Status</th>
<th>Campaign Name</th>
<th>URL Link</th>
<th>Product</th>
<th>Dates (Start to End)</th>
<th>Total Budget</th>
<th>Daily Budget</th>
<th>Pricing Model</th>
<th>Bid</th>
<th>Targeting Info</th>
<th>Total Units</th>
</tr>
</thead>
<tbody>
<tr>
<td>df</td>
<td>dfd</td>
<td>fdsd</td>
<td>fdsfd</td>
<td>dsf</td>
<td>dd</td>
<td>dd</td>
<td>dd</td>
<td>dd</td>
<td>dd</td>
<td>dd</td>
</tr>
</tbody>
</table>
</div>

HTML (assuming the thead doesn't change):
Add line
Delete line
<div style="width:98%; margin:0 auto">
<table align="center" id="table">
<thead>
<tr>
<th id="0">Status</th>
<th id="1">Campaign Name</th>
<th id="2">URL Link</th>
<th id="3">Product</th>
<th id="4">Dates (Start to End)</th>
<th id="5">Total Budget</th>
<th id="6">Daily Budget</th>
<th id="7">Pricing Model</th>
<th id="8">Bid</th>
<th id="9">Targeting Info</th>
<th id="10">Total Units</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
JavaScript:
<script type="text/javascript">
<!--
var line_count = 0;
//Count the amount of <th>'s we have
var header_count = $('#table > thead').children('th').length - 1;
$(document).ready(function() {
$('#add').click(function() {
//Create a new <tr> ('line')
$('#table > tbody').append('<tr></tr>');
//For every <th>, add a <td> ('cell')
for(var i = 0; i < header_count; i++) {
$('#table > tbody > tr:last-child').append('<td id="'+ line_count +'_'+ i +'"></td>');
}
line_count++; //Keep track of how many lines were added
});
//Now you still need a function for deleting.
//You could add a button to every line which deletes its parent <tr>.
});
-->
</script>

Related

Adding jquery 'each' function to js function

I have a datatable and there is a 'amount' column. I have a js function to seperate thousand and add currency mark to each amount in the table. However the function is not working on "each" row but only works on first row. When I google it, I understand that I need to add this function in a jquery each function. Could you help me about how to make this happen?
function numberWithCommas(x) {
return "₺"+x.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
var val = parseInt($('#tutar').text());
//Use the code in the answer above to replace the commas.
val = numberWithCommas(val);
$('#tutar').text(val);
<table class="table table-bordered" id="Piyasa" width="100%" cellspacing="0">
<thead>
<tr>
<th scope="col">No</th>
<th scope="col">Şirket</th>
<th scope="col">Alcaklı</th>
<th scope="col">Borçlanma Tarihi</th>
<th scope="col">Ödeme Tarihi</th>
<th scope="col">Tutar</th>
<th scope="col">Açıklama</th>
<th scope="col">Bilgi Güncelle</th>
</tr>
</thead>
<tfoot>
<tr>
<th colspan="5" style="text-align:right" >Toplam:</th>
<th></th>
<th></th>
</tr>
</tfoot>
<tbody>
{% for musteri in piyasa %}
<tr>
<th scope="row">{{musteri.id}}</th>
<td>{{musteri.sirket}}</td>
<td>{{musteri.alici}}</td>
<td>{{musteri.borc_tarih}}</td>
<td>{{musteri.odeme_tarih}}</td>
<td id="tutar">{{musteri.tutar|floatformat:2}}</td>
<td>{{musteri.aciklama}}</td>
<td>Güncelle</td>
</tr>
{% endfor %}
</tbody>
</table>
The first thing you should do is not re-use the same id for multiple elements on the page, which you're doing inside your server-rendered loop building up table rows.
Instead use a class, and then use that class to target all the matching elements. In the example below I have used the class format-number to indicate any cell I want to run the formatting code on.
function numberWithCommas(x) {
return "₺" + x.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
$(".format-number").each(function(){
const $this = $(this);
const currentVal = parseFloat($this.text());
$this.text( numberWithCommas(currentVal) );
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="format-number">10101.23</td>
</tr>
<tr>
<td class="format-number">345678.56</td>
</tr>
<tr>
<td class="format-number">123456789.45</td>
</tr>
</table>

I need to check if any <td> in a html table is empty/null as in after the page loads it only returns <td></td> and change it to <td><p>$0</p></td>

example of the table
<table class="tg">
<thead>
<tr>
<th class="tg-0lax" id="blank-spaces"></th>
<th class="titles" id="this">????</th>
<th class="titles">???<br></th>
<th class="titles">???</th>
<th class="titles">???</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>not empty do nothing</td>
<td></td>
</tr>
</tbody>
<table>
Now the way this is really written, data will be pushed into each td from an API, some times that API is down, and I would like to use jquery to check if a td has anything displaying in it and if it doesnt I want there to be a string with an error message in the td. This is the jquery im trying currently
var empty = $("td").trim().filter(function () { return this.value.trim() === null })
empty.addClass("errorDefault");
if ($("td").hasClass("errorDefault")) {
this.val("$0");
this.text("$0");
this.html("<p>There was an error getting data</p>");
}
There is no .trim() in jQuery
string trim() is not going to return null.
table cells do not have value
$("td").hasClass("errorDefault") only looks at first element
$("tbody td")
.filter((_, td) => !td.textContent.trim().length)
.addClass("errorDefault")
.text("$0");
.errorDefault {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tg">
<thead>
<tr>
<th class="tg-0lax" id="blank-spaces"></th>
<th class="titles" id="this">????</th>
<th class="titles">???<br></th>
<th class="titles">???</th>
<th class="titles">???</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>not empty do nothing</td>
<td></td>
</tr>
</tbody>
<table>
If it is truly empty, CSS can do it.
tbody td:empty{
background: red;
}
tbody td:empty:after {
content: "$0";
}
<table class="tg">
<thead>
<tr>
<th class="tg-0lax" id="blank-spaces"></th>
<th class="titles" id="this">????</th>
<th class="titles">???<br></th>
<th class="titles">???</th>
<th class="titles">???</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>not empty do nothing</td>
<td></td>
</tr>
</tbody>
<table>

I need to make the sum of an column in javascript [duplicate]

This question already has answers here:
How to sum a single table column using Javascript?
(3 answers)
How do I sum the price column from HTML table using JavaScript?
(4 answers)
Closed 1 year ago.
This is html code that i can't edit :
<table class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Expense name</th>
<th scope="col">Value per unity (lei)</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Water</td>
<td class="expense">62</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Netflix subscription</td>
<td class="expense">49.50</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Juice</td>
<td class="expense">16.40</td>
</tr>
<tr>
<th scope="row">4</th>
<td>New phone</td>
<td class="expense">2599</td>
</tr>
</tbody>
</table>
<h2>
Total expenses this month (lei):
<div id="total-expenses"></div>
</h2>
My question is :
How do i do that in code(javascript)?
I have something in my head but i don t know how to write that. What i have in head is: i declare variable for expenses,or using this queryselector(but i don t know how to point at specific td, because i have 2 td's in 1 tr) and after i can make a function with sum of that column, but i don't know how to write that in code. Can someone help me
First, you need to select all nodes that have .expense. Then you should iterate and calculate the total. After that write the total into #total-expenses.
// select nodes for expense
const expenceNodes = document.querySelectorAll('.expense');
let total = 0.0;
// calculating total
expenceNodes.forEach(node => {
total += parseFloat(node.innerText);
})
// write total
document.getElementById('total-expenses').innerText = total.toFixed(2);
<table class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Expense name</th>
<th scope="col">Value per unity (lei)</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Water</td>
<td class="expense">62</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Netflix subscription</td>
<td class="expense">49.50</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Juice</td>
<td class="expense">16.40</td>
</tr>
<tr>
<th scope="row">4</th>
<td>New phone</td>
<td class="expense">2599</td>
</tr>
</tbody>
</table>
<h2>
Total expenses this month (lei):
<div id="total-expenses"></div>
</h2>

Cut Div Content to table body with jquery

i have a table like this:
<table class="table">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Name</th>
<th scope="col">Family</th>
<th scope="col">Age</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div id="div1">
#foreach(var item in Model)
{
<tr>
<th>item.Id</th>
<td>item.Name</td>
<td>item.Family</td>
<td>item.Age</td>
</tr>
}
</div>
I want to cut div1 content and paste to table tbody tag with jquery
the result that i need is:
<table class="table">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Name</th>
<th scope="col">Family</th>
<th scope="col">Age</th>
</tr>
</thead>
<tbody>
#foreach(var item in Model)
{
<tr>
<th>item.Id</th>
<td>item.Name</td>
<td>item.Family</td>
<td>item.Age</td>
</tr>
}
</tbody>
</table>
also i use this code but doesn't work:
<script>
$(document).ready(function () {
$("#div1").replaceAll("tbody");
}
</script>
I tried with some jquery method but mostly copy all div(div tag with content)
but i need only cut content of div.
please help me
This might help you.
$('#div1').contents().appendTo('tbody')

How do you sort for row details in HTML?

I am using sorttable to sort my columns in table.
Now I have a table as follows:
<table class="sortable draggable">
<thead>
<tr>
<th class="col-salesOrderId">Order Number</th>
<th class="col-orderDate">Date of Order</th>
<th class="col-party">Party</th>
<th class="col-edit">Edit</th>
<th class="col-delete">Delete</th>
</tr>
</thead>
<tbody>
{#orders}
<tr>
<td class="col-salesOrderId">{.salesOrderId}</td>
<td class="col-orderDate">{#formatDate date=orderDate format="DD-MM-YYYY" /}</td>
<td class="col-party">{.party.partyName}</td>
<td class="col-edit">
<button class="btn btn-info btn-edit">
</button>
</td>
<td class="col-delete">
<button class="btn btn-danger btn-delete">
</button>
</td>
</tr>
<tr class="row-details">
<td>{.salesOrderId}</td>
<td colspan="4">
<table class="sortable draggable">
<thead>
<tr>
<th class="col-itemName">Item Name</th>
<th class="col-quantity">Quantity</th>
<th class="col-rate">Rate</th>
<th class="col-amount">Amount</th>
</tr>
</thead>
<tbody>
{#items}
<tr>
<td>{.item.itemName}</td>
<td>{.quantity}</td>
<td>{.rate}</td>
<td>{#math key="{.quantity}" method="multiply" operand="{.rate}"/}</td>
</tr>
{/items}
</tbody>
</table>
</td>
</tr>
{/orders}
</tbody>
</table>
Have you noted in the above mentioned table I have row details for each row?
Now when I click on a column header to sort it, I get the row details first and then I get all the main rows.
Here is how my table looks before sorting:
Here is how my table looks after sorting:
Is there any solution to this problem still using sorttable?
Update:
Here is sample jsFiddle
Row details are now sorted correctly as shown in the above jsFiddle. But now the problem is :
When you click on City column everything looks fine. Now if we again click on City Column, the row details are displayed before the actual rows which is wrong.
Please look at the images below for more information on problem:
After Clicking on City Column: (Which looks perfect)
After Clicking on City Column Again: (Expected for a developer but unexpected for a user)
I'am guessing but maybe the problem is the empty td beside the row details. I added first name as value and set css style display:none. Now the row details will be sorted also correctly.
Updated answer:
try to just nest the table inside the td like the below example.
Try this:
<table class="sortable">
<thead>
<tr>
<th>First Name</th>
<th>LastName</th>
</tr>
</thead>
<tbody>
<tr>
<td>Vishal</td>
<td> Sherathiya
<table>
<thead>
<tr>
<th>Degree</th>
<th>Percentage</th>
</tr>
</thead>
<tbody>
<tr>
<td>B.E.</td>
<td>67</td>
</tr>
</tbody>
</table>
<td>
</tr>
<tr>
<td>Nikunj</td>
<td>Ramani
<table>
<thead>
<tr>
<th>Degree</th>
<th>Percentage</th>
</tr>
</thead>
<tbody>
<tr>
<td>B.E.</td>
<td>80</td>
</tr>
<tr>
<td>M.E.</td>
<td>54</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td>Raj</td>
<td>Gosai</td>
</tr>
</tbody>
</table>

Categories

Resources