The html td is not updating via jquery - javascript

I have this little method which, on the first load, created a <tr> and some <td>'s. That works. But if the underlying data changes, the <td>'s are not updated. I'm not sure why.
function ParseJson(json, isFirstLoad)
{
json = $.parseJSON(json);
var tr;
for (var i = 0; i < json.length; i++) {
if (isFirstLoad === 1)
{
tr = $('<tr/>');
tr.append("<td id='" + json[i].LocationName + "'>" + json[i].LocationName + "</td>");
tr.append("<td id='" + json[i].LocationName + "Count'>" + json[i].Count + "</td>");
$('#MainTable').append(tr);
}
else
{
var td = $("#" + json[i].LocationName + "Count");
td.html = json[i].Count;
}
}
When isFirstLoad is 1, the html is rendered as I would expect. Example:
<tr>
<td id="ChemLab">ChemLab</td>
<td id="ChemLabCount">24</td>
</tr>
But the next time around, if the data has changed and someone has left the Chem Lab, the html for ChemLabCount does not change.
I have verified that the json being passed into this method is correct. Meaning, the count DOES indeed change. It just doesn't get displayed on the screen.

jQuery .html() is a function, not a property.
td.html(json[i].Count);

The problem comes from td.html = json[i].Count; because it's not the right way of using html() method.
To set the Count to your td you could use .text() instead :
td.text( json[i].Count );
Else if you want to set an HTML code the you could use .html() :
td.html( json[i].Count );

Related

How do I add data into html table using jquery?

I'm trying to add data from my firebase realtime database into a html table using jquery and javascript. I'm new to jquery, so I more or less have no idea what I'm doing.
I can retrieve the data but I can't add it to the table on the html page.
Is something wrong with this line?:
$("#table_body tbody").append("<tr><td>" + name.Name + "</td><td>" +
user.Email + "</td></td></td></tr>");
the table_body is just the table's id. The table remains empty.
pls help
You can add things to a table like this:
function productsAdd() {
$("#productTable tbody").append(
"<tr>" +
"<td>My First Item</td>" +
"<td>6/11/2019</td>" +
"<td>www.itemsite.com</td>" +
"</tr>"
);
}
Is this code running on load? Is this code wrapper in:
$(document).ready(function(){});
The document must be loaded before jQuery code can run properly, the function above ensures jQuery inside of it runs after the DOM has loaded
Example:
$(document).ready(function() {
let arr = [{n:'test', e:'ing'}, {n:'stuff', e:'ok'}];
for(let i = 0; i < arr.length; i++) {
$("#table_body tbody").append("<tr><td>" + arr[i].n + "</td><td>" + arr[i].e + "</td></tr>");
}
});

Extracting data from an HTML table

I have a table which shows these values.
turn-right
Go straight
turn-left
How do i get the 2nd value Go straight only ? I have this following codes.
var text = $('#personDataTable tr:first td:first').text();
This code above allows me to get the very first 'turn-right'. I tried to use
var text = $('#personDataTable tr:second td:first').text();
but it does not work.
This is the code i use to draw the table.
function drawTable(data) {
for (var i = 0; i < data.routes[0].legs[0].steps.length; i++) {
drawRow(data.routes[0].legs[0].steps[i]);
}
}
function drawRow(steps) {
var row = $("<tr />")
$("#personDataTable").append(row);
row.append($("<td>" + steps.maneuver + "</td>"));
console.log('Added Table');
}
This is my html
<table id="personDataTable">
<tr>
<th>Maneuver</th>
</tr>
</table>
tr:second is invalid CSS. The correct syntax is :
'#personDataTable tr:nth-child(2) td:first'

How do I look for the TD inside a TR that is below the TR that I click?

The purpose of this code is to make an ajax call if the <td> contained within the <tr> that is below the <tr> that was clicked, but only if the hidden <tr> is empty. Eventually I plan to take that data and do something with it, but for right now, I just need to get this thing which emulates an accordion as a table working. Due to this table being made on the same html file that I have other .hidden elements on, I had to create custom classes to hide these particular ones. The class detail-view makes it visible, and the class hidden-detail contains display:none. I know that postDetails works as far as finding the right data. What i'm more worried about is finding out why FireFox's dev tools say statusRow and detPane are marked as (unavailable) throughout this code, whereas statusRow.closest('tr').next('tr') actually appears to contain the row detPane, as intended. Is there something wrong with the jQuery or selectors? What's going on here?
function makeOrderTable(response, username, sesstoken) {
$(jQuery.parseJSON(JSON.stringify(response))).each(function() {
var foNum = this['Factory Order#'];
var pO = this['PO#'];
var status = this['Status'];
var shipDate = this['Ship Date'];
$('.orders tbody').append(
'<tr class="status-row">'+
'<td>' + foNum + '</td><td>' + pO + '</td><td>' + status + '</td><td>' + shipDate + '</td>'+
'</tr>'+
'<tr class="detail-row hidden-detail">'+
'<td colspan="4"></td>'+
'</tr>'
);
});
$(document).ready(function() {
$('table').on('click', 'tr.status-row', function() {
var statusRow = $(this);
var detPane = $(statusRow[0]).closest('tr').next('tr');
$('.detail-view').addClass('hidden-detail');
$('.detail-view').removeClass('detail-view');
detPane.addClass('detail-view');
detPane.removeClass('hidden-detail');
if (detPane.find('td').text == '')
{
var value = statusRow.find('td:first-child').text();
postDetails(value, username, sesstoken, detPane.find('td'));
}
});
});
}
The problem was that as epascarello pointed out, text isn't a valid property. Ergo, couldn't find anything. But, I also needed to grab the details td separately--i.e. couldn't access things from other things and just daisy-chain selectors all over the place. So, here's the end result.
function makeOrderTable(response, username, sesstoken) {
$(jQuery.parseJSON(JSON.stringify(response))).each(function() {
var foNum = this['Factory Order#'];
var pO = this['PO#'];
var status = this['Status'];
var shipDate = this['Ship Date'];
$('.orders tbody').append(
'<tr class="status-row">'+
'<td>' + foNum + '</td><td>' + pO + '</td><td>' + status + '</td><td>' + shipDate + '</td>'+
'</tr>'+
'<tr class="detail-row hidden-detail">'+
'<td colspan="4"></td>'+
'</tr>'
);
});
$(document).ready(function() {
$('table').on('click', 'tr.status-row', function() {
var statusRow = $(this);
var detRow = statusRow.closest('tr').next('tr');
var details = this.nextElementSibling.querySelector('td');
$('.detail-view').addClass('hidden-detail');
$('.detail-view').removeClass('detail-view');
detRow.addClass('detail-view');
detRow.removeClass('hidden-detail');
if (details.innerText == '')
{
var value = statusRow.find('td:first-child').text();
postDetails(value, username, sesstoken, details);
}
});
});
}
If I understand the question correctly, I think your selector for the "hidden" tr is incorrect.
You have the click event attached to the tr, so you shouldn't have to do .closest('tr'). Just var detPane = $(statusRow[0]).next('tr'); should get you the next tr after the one that was clicked.

jQuery selector unable to find table row class

Given an array of strings returned from an sql query, I am appending the data as rows into my html table via javascript:
loadUsers: function()
{ .
.
.
function displayUsersOnTable(response)
{
for(var i = 0; i < response.results.length; i++)
{
var contact = response.results[i];
var $newRow = $('<tr class="user-row">' +
'<td>' + contact.full_name + '</td>' +
'<td>' + contact.email + '</td>' +
'</tr>')
.data('user', contact);
$userTableBody.append($newRow);
}
}
}
Inside a different function that is called after loadUsers is called, I have this:
$('.user-row').click( function() {
window.alert("CLICKED");
});
When I run my site it won't register the click event. If I select the classes from my table row or table header it runs fine. I suspect the problem involves the fact that the table rows are dynamically generated. When I inspect element everything is in place. What am I missing?
try:
$(document).on('click', '.user-row', function() {
window.alert("CLICKED");
});

Programmatically creating <DIV>s and problems arise

I am new to javascript and have written a piece of code (pasted below). I am trying to build a little game of Battleship. Think of that game with a grid where you place your ships and start clicking on opponents grid blindly if it will hit any of the opponents ships. Problem is I need to get a function called with the ID of the DIV to be passed as a parameter. When the DIV is programmatically created like below, what will work. This? : --///<.DIV id='whatever' onclick='javascript:function(this.ID)' /> .. I saw sth like that somewhere .. this inside html :S
the js code is: (there are two grids, represented by the parameter - who - ... size of grid is also parametric)
function createPlayGround(rows, who)
{
$('#container').hide();
var grid = document.getElementById("Grid" + who);
var sqnum = rows * rows;
var innercode = '<table cellpadding="0" cellspacing="0" border="0">';
innercode += '<tr>';
for (i=1;i<=sqnum;i++)
{
var rowno = Math.ceil(i / rows);
var colno = Math.ceil(i - ((rowno-1)*rows));
innercode += '<td><div id="' + who + '-' + i +'" class="GridBox'+ who +'" onmouseover="javascript:BlinkTarget(' + i + ',' + who +');" onclick="javascript:SelectTarget('+ i + ',' + who +');" >'+ letters[colno - 1] + rowno +'</div></td>';
if (i % rows == 0)
{
innercode += '</tr><tr>';
}
}
innercode += '</tr></table>';
grid.innerHTML = innercode;
$('#container').fadeIn('slow');
}
It sounds like what you really want is to get the div element that was just clicked on. If you just want to return the div that was clicked on, all you have to do is use "this":
<div id="whatever" onclick="function(this)"></div>
If you're actually more interested in getting the id of the div clicked on, you can do this:
<div id="whatever" onclick="function(this.id)"></div>
However, it sounds like you just want the id so that you can get the div using getElementById, and the first code snippet will help you skip that step.
Instead of creating the inner html from strings you can create it with jQuery and add event listeners like so:
$("<div></div>")
.click(function(e) {
selectTarget(i, who);
})
.appendTo(container);

Categories