How to populate a table td - javascript

I've created a table and I need to populate the tds using JavaScript because the data is coming from the server.
Here is my table:
<table id="report" class="infoRecurso" id='testExportId' style="width: 100%; color: #363636">
<thead style="color: #363636">
<tr class='btn-danger' style="background-color: lightgray; color: #363636">
<th class="thData">Data</th>
<th id="timeIniticial" class="thInicio">Início</th>
<th class="thTermino">Término</th>
<th class="thDuracao">Duração</th>
<th class="thAtividades">Atividades</th>
</tr>
</thead>
<tbody id="myTable">
<tr>
<td style="text-align: left;"></td>>
<td id="inicialTime"></td>
<td>Hora Final</td>
<td style="text-align: left;">Duração</td>
<td colspan="1" class="quebraLinha" style="text-align: left;"></td>
</tr>
<tr>
<th class="horasTotaisTh" colspan="3"> Horas Totais </th>
<th class="resultadoHorasTotaisTh" colspan="4">Hora Total</th>
</tr>
</tbody>
I am trying to populate the td with the id inicialTime that is corresponding to the tr timeIniticial. I've tried using this code:
var data = [{"product": "RD0"}, {"product": "RD1-184"}, {"product": "RD1-185"}];
var table = $('.infoRecurso');
$.each(data, function(i, value) {
table.find('tr').eq(i).find("td[id='inicialTime']").text(value.product);
});
but this code only populates the first position.
How can I populate the rest of tds positions?

Your question leaves a few points open, so I can only guess what you really want. In the following snippet I have compiled a solution that will .prepend() some html code to your table, to the effect that your second column is always filled with the code from your data array. I changed the id attribute of this <td> element to class since IDs must always be unique.
I also "corrected" your colspan attributes of the last table row since there are only 5 columns in total.
var data = [{"product": "RD0"}, {"product": "RD1-184"}, {"product": "RD1-185"}];
var html=data.map(({product})=>
`<tr><td></td><td class="inicialTime">${product}</td><td>Hora Final</td>
<td>Duração</td><td class="quebraLinha"></td></tr>`).join('')
$('.infoRecurso tbody').prepend(html);
td {text-align:left}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="report" class="infoRecurso" id='testExportId' style="width: 100%; color: #363636">
<thead style="color: #363636">
<tr class='btn-danger' style="background-color: lightgray; color: #363636">
<th class="thData">Data</th>
<th class="thInicio">Início</th>
<th class="thTermino">Término</th>
<th class="thDuracao">Duração</th>
<th class="thAtividades">Atividades</th>
</tr>
</thead>
<tbody id="myTable">
<tr>
<th class="horasTotaisTh" colspan="3"> Horas Totais </th>
<th class="resultadoHorasTotaisTh" colspan="2">Hora Total</th>
</tr>
</tbody>

Related

How to update a td value from a table with id using jQuery

I am trying to work out how to update the value of the table cell for each row using jQuery.
I basically update the td#11_p value from the table, but it's not updated. I tried following jQuery,
$('#test').click(function() {
var oldprirce = $("#11_p").val();
$("#11_p").val(+(oldprirce) + +(15));
jQuery("#PDList").trigger("liszt:updated");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="pdsDetails" border=" 1px solid black" class="table table-bordered table-striped datatable dt-responsive nowrap" style="width: 100%; ">
<thead>
<tr>
<th>Product Name</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody id="PDList">
<tr id="11_row">
<td>PARACHUTE HAIR OIL 50ml</td>
<td id="11_q">1</td>
<td id="11_p">20</td>
</tr>
<tr id="12_row">
<td>HAIR OIL 50ml</td>
<td id="12_q">2</td>
<td id="12_p">30</td>
</tr>
</tbody>
</table>
<button id="test">change</button>
https://jsfiddle.net/SathishNcc/1dusLhrv/16/
Only form control elements have a value property. td elements just have text or HTML content which can be read and updated.
Given your goal of wanting to add 15 to the current integer in the cell you can provide a function to text() which accepts the current content as a string argument, convert it to a float (as it's a price) and then add 15 to it before returning it to the function for it to update the DOM. Try this:
$('#test').click(function() {
$("#11_p").text((i, t) => parseFloat(t) + 15);
jQuery("#PDList").trigger("liszt:updated");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="pdsDetails" border=" 1px solid black" class="table table-bordered table-striped datatable dt-responsive nowrap" style="width: 100%; ">
<thead>
<tr>
<th>Product Name</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody id="PDList">
<tr id="11_row">
<td>PARACHUTE HAIR OIL 50ml</td>
<td id="11_q">1</td>
<td id="11_p">20</td>
</tr>
<tr id="12_row">
<td>HAIR OIL 50ml</td>
<td id="12_q">2</td>
<td id="12_p">30</td>
</tr>
</tbody>
</table>
<button id="test">change</button>
You could change $("#11_q").val(); to $("#11_q").html();

Bootstrap: data-sort on dynamic table

I have a bootstrap table as follows:
<table id="fullDataTable"
class="table table-bordered"
data-toggle="table"
data-classes="table"
data-striped="true"
data-sort-name="numFrame"
data-sort-order="desc">
<thead>
<tr>
<th class="col-sm-1"
data-field="numFrame"
data-sortable="true">numFrame</th>
<th class="col-sm-1"
data-field="timeStamp"
data-sortable="false">timeStamp</th>
<th class="col-sm-1"
data-field="id_robot"
data-sortable="false">idRobot</th>
</tr>
</thead>
<tbody id="dataTable">
</tbody>
</table>
The table is then filled dynamically with values from a MySQL database with Javascript:
socket.on('gotDataQuality', function(message) {
if(message == 0){
alert('No Quality datas for this session');
clearElement("dataTable");
}else{
clearElement("dataTable");
for (var i = message.length-1; i >= 0; i--) {
$('#dataTable').prepend('<tr><td>'+message[i].numFrame+'</td><td>'+message[i].timeStamp+ '</td><td>'+message[i].idRobot+'</td></tr>');
}
}
});
The table fills correctly but when I attempt to sort it (by clicking on one of the sortable headers) the contents of the table is erased. I'm not entirely sure how the data-sort element works, what can I do to resolve this?
You can use List JS
You can make use of this example
var options = {
valueNames: [ 'id', 'firstname', 'lastname','username' ]
};
var userList = new List('table', options);
.table [data-sort] {
cursor: pointer;
}
.table [data-sort]::after {
margin-left: .25rem;
content: url('data:image/svg+xml;utf8,<svg width=\'6\' height=\'10\' viewBox=\'0 0 6 10\' fill=\'none\' xmlns=\'http://www.w3.org/2000/svg\'><path fill-rule=\'evenodd\' clip-rule=\'evenodd\' d=\'M3 0L6 4H0L3 0ZM3 10L0 6H6L3 10Z\' fill=\'%238898aa\'/></svg>');
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<div id="table">
<table class="table">
<thead>
<tr>
<th scope="col" class="sort" data-sort="id">#</th>
<th scope="col" class="sort" data-sort="firstname">First Name</th>
<th scope="col" class="sort" data-sort="lastname">Last Name</th>
<th scope="col" class="sort" data-sort="username">Username</th>
</tr>
</thead>
<tbody class="list">
<tr>
<th scope="row" class="id">1</th>
<td class="firstname">Mark</td>
<td class="lastname">Otto</td>
<td class="username">#mdo</td>
</tr>
<tr>
<th scope="row" class="id">2</th>
<td class="firstname">Jacob</td>
<td class="lastname">Thornton</td>
<td class="username">#fat</td>
</tr>
<tr>
<th scope="row" class="id">3</th>
<td class="firstname">Larry</td>
<td class="lastname">the Bird</td>
<td class="username">#twitter</td>
</tr>
</tbody>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.min.js"></script>
CodePen

Loop table to even row amount in JQuery

The question I have a table pulling from the backend for events, will list out in the font in 3 different column with specific categories, but sometimes only have 1 event or 2, but I need to at least display 3 items.
So I try to use jQuery each function to check how many rows in the table if only have 1 add 2 rows if only have 1 row add 2 instead.
So the table will be same height no matter how many events display.
My code doesn't work correctly, so I was hoping anyone can help me out with this.
Here's my sample code:http://jsfiddle.net/s2devfrg/
Here's the jQuery:
jQuery(function(){
jQuery('#table-amount tbody').each(function(){
let number =jQuery(this).find('tr').length;
console.log('amount' + number);
//if table only have one add two extra row
if(number === 1){
jQuery(this).append("<tr> </tr>");
jQuery(this).append("<tr> </tr>");
} else {
//if table only have two add one roe
if(number === 2 ){
jQuery(this).append("<tr> </tr>");
}
}
})
})
The selector you are using on .each is wrong. There are no elements with the passed id.
Also there are couple of blank tr's in your html which I have removed.
Try this code below:
jQuery(function(){
jQuery(".table tbody").each(function(){
let number =jQuery(this).find('tr').length;
console.log('amount' + number);
//if table only have one add two extra row
if(number === 1){
jQuery(this).append("<tr><td> </td></tr><tr><td> </td></tr");
} else if(number === 2 ){
jQuery(this).append("<tr><td> </td></tr>");
}
})
})
.row {
background: #f8f9fa;
margin-top: 20px;
}
.col {
border: solid 1px #6c757d;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--
Bootstrap docs: https://getbootstrap.com/docs
-->
<div class="container">
<div class="row">
<div class="col">
<table class="table">
<thead class="table-amount">
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
</tbody>
</table>
</div>
<div class="col">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
</tr>
</tbody>
</table>
</div>
<div class="col">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Updated fiddle link
I have reviewed you sample code, first of all kindly note that in jQuery
when you find tr it will count total number of rows including tr inside thead.
So your
total counts are always one more than actual rows.
Second thing you should not append just tr you should provide same structure
as in
your existing rows.
Also in first table structure you had one extra th may be typo.
In first and third table structure you have one tr extra with empty
structure
instead, you should have same structure as you have for others.
here is the link for modified JS Fiddle link
https://jsfiddle.net/patelmurtuza/kj8zgqad/

Get value of hidden label in table using jquery?

I have an html table within a list view, and have a hidden label in it called "vehicle_num". I am able to get the selected row of the table, as well as any of the td, however I cannot seem to get the value of the label. I have tried:
var vehicle_number = $(this).closest('tr').children('#vehicle_num').text();
Below is the code for the listview. How can I get the value of the label?
<asp:ListView ID="lvEquipmentList" runat="server" DataKeyNames="vehicle_number">
<LayoutTemplate>
<table id="table-equipment-list" class="table table-list">
<thead>
<tr>
<th scope="col" class="product-line">Product line</th>
<th scope="col" class="model-number">Model #</th>
<th scope="col" class="serial-number">Serial #</th>
<th scope="col" class="dar-status">DAR Status</th>
<th scope="col" class="ship-date">Ship Date</th>
</tr>
</thead>
<tbody>
<asp:PlaceHolder ID="ItemPlaceholder" runat="server" />
</tbody>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<th scope="row" class="product-line"><div class="icon"><img src='<%#Eval("image_path")%>' onerror="this.src='assets/images/placeholder.png';" alt=""/></div> <span class="line-title"><%#Eval("product_line")%></span></th>
<td class="model-number"><%#Eval("model")%><label class="vehicle_num" hidden="hidden"><%#Eval("vehicle_number")%></label></td>
<td class="serial-number"><%#Eval("serial_number")%></td>
<td class="dar-status"><img src='<%#Eval("display_status") %>'/></td>
<td class="ship-date"><%#Eval("date")%></td>
</tr>
</ItemTemplate>
<EmptyDataTemplate>
<table id="table-equipment-list" class="table table-list">
<thead>
<tr>
<th scope="col" class="product-line">Product line</th>
<th scope="col" class="model-number">Model #</th>
<th scope="col" class="serial-number">Serial #</th>
<th scope="col" class="dar-status">DAR Status</th>
<th scope="col" class="ship-date">Ship Date</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row" class="product-line"><div class="icon"></div> <span class="line-title"></span></th>
<td class="model-number"></td>
<td class="serial-number"></td>
<td class="dar-status"></td>
<td class="ship-date"></td>
</tr>
</tbody>
</table>
</EmptyDataTemplate>
</asp:ListView>
EDIT
I have edited the code above to put the label in a table column. I was able to get the value using:
var vehicle_number = $(this).closest('tr').find('.vehicle_num').text();
This is invalid markup:
<tr>
<th scope="row" class="product-line"><div class="icon"><img src='<%#Eval("image_path")%>' onerror="this.src='assets/images/placeholder.png';" alt=""/></div> <span class="line-title"><%#Eval("product_line")%></span></th>
<td class="model-number"><%#Eval("model")%></td>
<td class="serial-number"><%#Eval("serial_number")%></td>
<td class="dar-status"><img src='<%#Eval("display_status") %>'/></td>
<td class="ship-date"><%#Eval("date")%></td>
<label id="vehicle_num" hidden="hidden" runat="server"><%#Eval("vehicle_number")%></label>
</tr>
There's an errant label as a child of a tr, which isn't valid. When the browser tries to make sense of this, it could be doing anything with that label to construct a valid DOM, which is going to effect your jQuery selectors.
The label needs to be in a table cell:
<tr>
<th scope="row" class="product-line"><div class="icon"><img src='<%#Eval("image_path")%>' onerror="this.src='assets/images/placeholder.png';" alt=""/></div> <span class="line-title"><%#Eval("product_line")%></span></th>
<td class="model-number"><%#Eval("model")%></td>
<td class="serial-number"><%#Eval("serial_number")%></td>
<td class="dar-status"><img src='<%#Eval("display_status") %>'/></td>
<td class="ship-date"><%#Eval("date")%></td>
<td><label id="vehicle_num" hidden="hidden" runat="server"><%#Eval("vehicle_number")%></label></td>
</tr>
(Or, if it's always hidden anyway, you can probably put it in an existing table cell. Either way should work.)
Additionally, if the client-side id is being explicitly set here, then any repetition of these records will result in duplicate ids in the DOM, which is also invalid. Different browsers respond to id-based selectors in different ways when there are duplicate ids, because the behavior is undefined. You probably want to use a class instead:
<label class="vehicle_num" ...
Since the label is no longer a child of the tr but rather a descendant of it, use find() instead of children():
$(this).closest('tr').find('.vehicle_num')

jquery working in firefox but not in chrome

Ok i know this might sound like a duplicate question, as a lot of questions have been asked like this one...but i have looked into almost all of them and could not find what the solution.
Ok I am getting the following response from the server using normal ajax call:
<form id="ctl00" name="ctl00" method="post" action="RatesGrids.aspx?pt=EMPL&RT=bill">
<div>
<input id="__VIEWSTATE" type="hidden" name="__VIEWSTATE" value="/wEPDwUENTM4MQ9kFgJmD2QWAmYPPCsADQEADxYCHgtfIUl0ZW1Db3VudAICZGQYAQUMZ3JkQmlsbFJhdGVzDzwrAAoBCAIBZE4pvNtSHIbu7h7ISmN42ktJBm5R">
</div>
<div>
<table id="grdBillRates" class="tableView" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
<thead>
<tr class="tableViewHeader">
<th scope="col" style="white-space:normal;">Emp. Id</th>
<th scope="col" style="white-space:normal;">Last Name</th>
<th scope="col" style="white-space:normal;">*Res Usage</th>
<th scope="col" style="white-space:normal;">Source</th>
<th scope="col" style="white-space:normal;">Eff. Date</th>
<th scope="col" style="white-space:normal;">*Bill 1</th>
<th scope="col" style="white-space:normal;">*Bill 2</th>
<th class="display_none" scope="col" style="white-space:normal;"></th>
<th class="display_none" scope="col" style="white-space:normal;">Time Stamp</th>
<th scope="col" style="white-space:normal;">Currency</th>
</tr>
</thead>
<tbody>
<tr class="tableViewRow" onclick="loadrowitems(0,this)" onmouseover="this.style.cursor='default';">
<td style="width:100px;white-space:normal;">10000000034 </td>
<td style="width:125px;white-space:normal;">Khan</td>
<td style="width:125px;white-space:normal;"></td>
<td style="width:80px;white-space:normal;">Local</td>
<td style="width:80px;white-space:normal;">12/04/2012</td>
<td align="right" style="width:80px;white-space:normal;">3.6500</td>
<td align="right" style="width:80px;white-space:normal;">6.0000</td>
<td class="display_none" style="width:0px;white-space:normal;">Z-C$ </td>
<td class="display_none" style="white-space:normal;">0,0,0,0,1,107,21,255</td>
<td style="width:70px;white-space:normal;">Z-C$</td>
</tr>
<tr class="tableViewAlternatingRow" onclick="loadrowitems(1,this)" onmouseover="this.style.cursor='default';">
<td style="width:100px;white-space:normal;">10000000034 </td>
<td style="width:125px;white-space:normal;">Khan</td>
<td style="width:125px;white-space:normal;">444 </td>
<td style="width:80px;white-space:normal;">Local</td>
<td style="width:80px;white-space:normal;">12/04/2012</td>
<td align="right" style="width:80px;white-space:normal;">2.1000</td>
<td align="right" style="width:80px;white-space:normal;">3.2000</td>
<td class="display_none" style="width:0px;white-space:normal;">Z-C$ </td>
<td class="display_none" style="white-space:normal;">0,0,0,0,1,107,21,254</td>
<td style="width:70px;white-space:normal;">Z-C$</td>
</tr>
</tbody>
</table>
</div>
</form>
Now i have to append the table in response in <div id="grdRates"></div>.
The application i am working on was created only keeping IE in mind, so it was catered using the following code:
if (contents) {
var table;
if ($(contents).find('table').length > 0)
table = $(contents).find('table')[0].xml
if (table) {
$('#grdRates').parent().show();
$('#grdRates').html(table);
}
}
above code was not working in Firefox as well as Chrome , was giving that xml as undefined and never showing the results, so i tried the following:
if (contents) {
var table;
if ($(contents).find('table').length > 0)
if ($.browser.msie)
table = $(contents).find('table')[0].xml
else
table = $(contents).find('#grdBillRates');
if (table) {
$('#grdRates').parent().show();
if ($.browser.msie)
$('#grdRates').html(table);
else
$('#grdRates').html(table.parent().html());
}
}
}
Note the #grdBillRates is the table id in the above HTML. Now this is working fine in firefox (showing the grid fine) but i have tried almost everything for chrome, but no luck....
And one more thing i cannot change the DLL so the solution has to be using script. Any help will be appreciated guys...Thanks
is there any error?
did you try to append it? something like this:
if (contents) {
var table = $(contents).find('#grdBillRates');
if (table.length > 0)
$('#grdRates').parent().show().append(table);
}
}

Categories