...

View Full Version : HTML table adds new row drops the end



SeattleMicah
03-19-2012, 06:10 PM
Hello, I have a goal in mind of creating a html table that is dynamically updated via JS. My goal is to have simple data displayed in table and have the top row replaced in intervals, which then moves all the other data down and deletes the final row.

I am in planing stage so I am searching for methods you all may know of, also what kind of html skeleton should I build, would a simple table do the trick? Do I need to attach ids to my rows?

Thanks -Micah

VIPStephan
03-19-2012, 08:22 PM
Well, the approach depends on the environment in which the functionality is going to be used. Is it a controlled system or for the general public? Being a friend of progressive enhancement, my approach would be this:

At first assume that JavaScript is not present/available and think about how it should work in a very basic way. The data needs to be stored somewhere and retreived from there so I guess some kind of server side functionality must be there already. In this case you can include a button to manually reload the page and update the table that way. The next step is to add the dynamic functionality so that the data is received and the tble updated on the fly, without reloading the entire page. This is done with asynchronous JavaScript and XML (AJAX).

So, in this case, I would say, you have a regular HTML table on first page load with the latest data, and then you’d add the JS functionality to load the new data, append a row to the table, and remove the last row at the same time (once data retreival was successful). The best way to add a chunk of HTML is to use document fragments (http://ejohn.org/blog/dom-documentfragments/).

Although it can be done with plain JS, a framework like jQuery, mootools, Dojo, YUI, or whatever can make things easier.

SeattleMicah
03-19-2012, 11:41 PM
Thank you for the response.

Basically it is a local environment at work, I have not created the means of accessing our database but I was thinking a php relationship using as you mention ajax/xml or json means or asynchronous loading the data. There will be no manual refresh, as soon as the index is loaded the table will be displayed and the content will be refreshed.

Old Pedant
03-20-2012, 12:01 AM
One fair warning: the HTML protocol, which include any AJAX-based communications, is strictly a "pull" protocol. That is, the client (browser) must make a request of the server, the server responds once, and then the connection is broken. For something else to happen, another request/response pair must be used. And so on.

This means that any "interval" based refresh of data in the browser must be initiated by browser-side code (e.g., typically via a setTimeout( ) JavaScript call).

So your JS code *PROBABLY* needs to handle the cases where (a) NO changes have occurred on the server (so nothing is changed in the <table> display), (b) one change has been made, and (c) MORE than one change has occurred on the server, meaning that more than one row may need to be added in the browser and more than one row dropped from the end. You can't depend on there always being one and only one change on the server.

webdev1958
03-20-2012, 12:35 AM
Hello, I have a goal in mind of creating a html table that is dynamically updated via JS. My goal is to have simple data displayed in table and have the top row replaced in intervals, which then moves all the other data down and deletes the final row.

This is fairly straight forward, especially if the data doesn't beed to come from the server after the page has loaded. If it does, it's fairly easy to send an AJAX request to the server to get the data you want and then replace the first row in the html table with the new data and then delete the last row. The server side coding should not be complicated unless you are doing something unusual.

I wouldn't use a javascript framework for this. The plain javascript is fairly minimal and will definitely be less code than if you use jQuery.

SeattleMicah
03-20-2012, 12:40 AM
Ok great information, thank you Old. I am in a very controlled environment and have been given the freedom to experiment, could this be a good time to try web sockets? And am I right to think that it may be a substitute too the technique of making the various ajax calls? I might be way off, I don't know to much about web sockets or ajax.

Thanks for the info though this is leading me in the right direction.

Old Pedant
03-20-2012, 01:55 AM
I haven't mucked with web sockets, but yes, they should work. You could also use a Java applet, of course. Java *is* allowed to use "push" technology.

But, really, I see nothing wrong with using AJAX and "pull" if the site isn't heavily loaded. I don't know how often you need to check for updates on the server. But once a second, if you don't have more than a dozen or so simultaneous users, wouldn't put a strain on the server. If you can live with once every 10 seconds, then you can have more users, etc.

And handling multiple results from the server wouldn't be hard. Just use a loop on the incoming data, adding one row (and deleting one row) at a time. It will be more than fast enough.

SeattleMicah
03-20-2012, 02:08 AM
awesome thank you, it will just be displayed on our front display in the office so technically one "user". I will try both ways just to play with different techniques, thank you.

Old Pedant
03-20-2012, 02:17 AM
Yeah, I did something similar for a "Sales Board".

It doesn't add/remove rows, but it scrolls the set of rows upward on the screen. All the salespeople are given one row each. As they make a sale, it registers in their row and plays a short musical selection they have chosen (15 seconds). Because of the music, it queues up the updates, so if another one (or more) comes in before the music finishes, it hold off displaying it. Oh, and the scroll is fast forwarded to the person who made the sale and the scrolling is stopped while the music plays.

Was fun to do and not hard. And it polls once a second using AJAX, too.

I thought it was kind of hokey when I did it, but the sales people love it. They taunt someone if their song hasn't been played by lunch break, for example.

SeattleMicah
03-20-2012, 03:16 AM
haha thats pretty cool. Where do they go when they scroll up? I am confused.

My next step is to find a good tutorial on manipulating the table. Do you have some good places when I could learn from? http://jsfiddle.net/AQ7WW/ (http://jsfiddle.net/AQ7WW/)maybe something like that?

SeattleMicah
03-20-2012, 07:24 AM
By environment do you mean languages? I will start with a ajax/jquery/html5 front-end environment, I will get my data from mysql/php.

Old Pedant
03-20-2012, 07:59 AM
The easiest way, which works in browsers supporting DOM level 2 (includes MSIE 8):


function addRowAndScroll( contentsToAdd, cellClasses ) /* arguments are arrays of same size */
{
var tbl = document.getElementById("idOfYourTable");
var row = tbl.insertRow(0);
for ( var c = 0; c < contentsToAdd.length; ++c )
{
var cell = row.insertCell( );
cell.className = cellClasses[c]; // omit of course if you don't pass in the classes
cell.innerHTML = contentsToAdd[c];
}
// then remove the last row:
tbl.deleteRow( tbl.rows.length - 1 );
}


You can of course add content to the cells any way you want. That just shows an easy way to do it, by passing in an array of content.

And that just shows one way you could specify the classes to apply to each column of cells.

***************

To scroll on the screen, I just adjust the scrollTop property of the <body> and, as a row is scrolled off the top of the screen, I move it from the top row in the <table> to the bottom row. Several ways to do that. You could just clone the row contents from top row to new bottom row and then delete the top row, for example.

Old Pedant
03-20-2012, 08:04 AM
BemleyCeuben's comment was an attempted SPAM. He was trying to advertise some URL, but the forum software removed the URL link.

Didn't you notice that his post was a verbatim copy of part of VIPStephan's post #2? First line thereof, in fact.

I've reported him.

SeattleMicah
03-20-2012, 08:25 AM
haha thank you very much pedant ill check this out in the morning.

Forum spam is the worst the most annoying part of my day as Im sure for more forums. And I think I set a record for highest percentage of spam per threads started on CF, I swear I always get at least 2 in my threads.

Old Pedant
03-20-2012, 08:32 AM
What? Giving up this early? I'll come pound on your door and make you finish tonight.

(I'm in Snohomish.)

anuradha chawla
03-20-2012, 12:16 PM
Below is the source code try this it may be helpful to you:
<html>
<head>
<script language="javascript">
function rowAdd(tableID) {

var table = document.getElementById(tableID);

var countRow = table.rows.length;
var row = table.rowInsert(countRow);

var cell1 = row.cellInsert(0);
var elmnt1 = document.createElement("input");
element1.type = "checkbox";
cell1.appendChild(elmnt1);

var cell2 = row.cellInsertl(1);
cell2.innerHTML = countRow+ 1;

var cell3 = row.cellInsert(2);
var eemnt2 = document.createElement("input");
element2.type = "text";
cell3.appendChild(elmnt2);

}

function rowDelete(tableID) {
try {
var table = document.getElementById(tableID);
var countRow = table.rows.length;

for(var i=0; i<countRow ; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
countRow --;
i--;
}

}
}catch(e) {
alert(e);
}
}

</script>
</head>
<body>

<input type="button" value="Add Row" onclick="rowAdd('dataTable')" />

<input type="button" value="Delete Row" onclick="rowdelete('dataTable')" />

<table id="dataTable" width="350px" border="1">
<tr>
<td><input type="checkbox" name="chk"/></td>
<td> 1 </td>
<td> <input type="text" /> </td>
</tr>
</table>

</body>
</html>

Info by- DHost

SeattleMicah
03-20-2012, 07:12 PM
haha nice Ill be up there tonight at the indoor soccer arena, and I was dead tired, needed to sleep.

I think I would like to head towards a jQuery route vs pure JS. From what I understand it will be easier to expand on maybe if I want the last row to fade off or whatever. http://stackoverflow.com/questions/1067828/jquery-and-adding-row-to-table

SeattleMicah
03-20-2012, 08:53 PM
I can't figure what I am doing wrong...



<script type="text/javascript" src="jquery-1.4.4.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var $destTable = $("#mainTable");
$("button#btnAdd").click(function() {
//Take the text, and also the ddl value and insert as table row.
var $newRow = $("<tr><td>hi</td><td>hi</td><td>hi</td></tr>");
$("#mainTable").append(newRow);
});
});
</script>


</head>
<body>
<div id="container">
<h1>Data Vizualization</h1><!--possible logo-->
<div id="map"><img src="images/map2.jpg" width="800"/></div><!--dynamic map-->
<table id="mainTable" border="1" cellspacing="0"><!--dynamic table-->
<tr>
<td class="icon"><img src="images/piicon.png" /></td>
<td class="timestamp">3/18/2012</td>
<td class="location">Boston, MA</td>
</tr>
</table>
<button id="btnAdd" type="button">Click Me!</button>
</div>

</body>
</html>

Old Pedant
03-20-2012, 09:32 PM
Well, for starters, I don't use jQuery. But I would certainly expect that a method named append would put the row LAST instead of first, which is not at all what you want.

But more importantly, you are trying to append *TEXT* to an object when what you need is to append a ROW. Appending text to a <table> is meaningless.

I really think in this case you may well be better off without using jQuery, but that's up to you. In any case, I'm sure you need to first AT LEAST create a "TR" element.

SeattleMicah
03-20-2012, 09:42 PM
ah yes good point I think there is a prepend function to solve that.

And I am confused what you mean by adding text, shouldn't the function add var $newRow = $("<tr><td>hi</td><td>hi</td><td>hi</td></tr>");

Old Pedant
03-20-2012, 09:50 PM
And I am confused what you mean by adding text, shouldn't the function add var $newRow = $("<tr><td>hi</td><td>hi</td><td>hi</td></tr>");

No. NOT AT ALL!

You can *ONLY* append *OBJECTS*. Text is *NOT* an object.

You could *probably* do


$("button#btnAdd").click(function() {
var newRow = document.createElement("tr"); // may be a jQuery way to do this
newRow.innerHTML = "<td>hi</td><td>hi</td><td>hi</td>";
$("#mainTable").append(newRow);
});

But it's usually a crappy idea to create objects via the use of innerHTML (in this case, you'd be creating 3 <td> objects via the innerHTML). Where possible, only use innerHTML to add textual content. (Even then, you can avoid it: You can use document.createTextNode() instead, which is better.)

Even if using jQuery, I'd create the <tr> and <td> elements as I showed you.

SeattleMicah
03-20-2012, 10:01 PM
ah ya duh.

VIPStephan
03-20-2012, 10:47 PM
OldPedant, jQuery correctly converts the strings to what you mean, i. e. it doesn’t treat var $newRow = $("<tr><td>hi</td><td>hi</td><td>hi</td></tr>"); as string but converts it to (inner)HTML (with the difference that the single nodes can be accessed and manipulated afterwards).

The error in Micah’s code was the missing dollar sign:


var $newRow = $("<tr><td>hi</td><td>hi</td><td>hi</td></tr>");
$("#mainTable").append($newRow);

It correctly appends a new row with three cells if the variable reference is correct.

And Micah, if you’re using jQuery, don’t use an outdated version. We’re at version 1.7.1 already.

Old Pedant
03-20-2012, 10:56 PM
Oh...I guess I see why!

Because it's not just


var $newRow = "<tr><td>hi</td><td>hi</td><td>hi</td></tr>";

It uses the magic $( ) function!


var $newRow = $("<tr><td>hi</td><td>hi</td><td>hi</td></tr>");


I can see HOW it *COULD* work, but I'm curious as to WHY it works. Why does jQuery know to convert that string into a set of objects? Why does it know that what was given isn't a locator or some sort??? I know that $("#id") means "find the object with the given ID" and $(".class") means "find objects of the given class." But are you saying that the presence of the "<" there triggers the conversion from HTML to object??

SeattleMicah
03-20-2012, 11:07 PM
Thanks Stephan, did you test the code? I added the $ and the change was not enough to make everything work for me. I updated my jquery as well...

SeattleMicah
03-21-2012, 12:03 AM
Ok I got it now...


<script type="text/javascript">
$(document).ready(function() {
var destTable = $("#mainTable");
$("#btnAdd").click(function() {
//Take the text, and also the ddl value and insert as table row.
var newRow = $("<tr><td>hi</td><td>hi</td><td>hi</td><td>hi</td><td>hi</td></tr>");
$("#mainTable tbody").prepend(newRow);
});
});
</script>

Old Pedant
03-21-2012, 12:18 AM
Still curious how jQuery knows to convert that string to a set of objects. Ah, well.

SeattleMicah
03-21-2012, 12:23 AM
black magic, muwhaha. what you said makes sense to me, ill ask on their forums.

SeattleMicah
03-21-2012, 12:41 AM
here you go Pedant http://api.jquery.com/jQuery/#jQuery2

SeattleMicah
03-21-2012, 12:42 AM
why dont you use jquery?

Old Pedant
03-21-2012, 01:01 AM
Bizarre. But this part bothers me:

In most cases, jQuery creates a new <div> element and sets the innerHTML property of the element to the HTML snippet that was passed in.
Creating a <div> element that in turn converts your string by using innerHTML won't work. You can't then append a <div> to a <table>. So if the code does work--and you say it does--then jQuery must do more than what that statement says.

Anyway, did you read the rest of the caveats in there re what can and can't happen? I still think this is a bad idea. I think you really should create the elements one at a time, just to be sure you get exactly what you need. If it happens to work for what you are using, great. But if nothing else there has to a bunch of overhead in parsing out your string and figuring out what to do with it.

webdev1958
03-21-2012, 01:15 AM
why dont you use jquery?

I don't use jquery either :)

After all, jquery is nothing more than a bunch of javascript functions prewritten by someone else to perform designated tasks.

There is nothing whatsoever that can be done with jquery that cannot be done with plain ol' javascript. And that is because jquery is just javascript. Jquery is not a different language or technology to javascript.

Sure, jquery has its place and in a production environment where you need to spit out code quickly, it can save time. But to perform a given task, no matter how simple it may be, the amount of code jquery runs in the background to perform that task will be many, many times greater than the code required if done in just plain vanilla javascript.

Over the years I have built my own js library of functions and so I have no need for jquery.

Finally, there are way too many people trying to take the "jquery" shortcut to learning javascript without learning the basic fundamentals and concepts of javascript first.

It's amazing how many noobies come waltzing into forums like this, dragging their broken jquery code in behind them on the floor looking for help because they don't know the basics of javascript.

just my 2c worth :)

Old Pedant
03-21-2012, 03:02 AM
just my 2c worth

Oh, I think it's worth more than that. $2 at least!

SeattleMicah
03-21-2012, 09:44 AM
haha I feel bad for being a noobie now!!! Saving time though, isn't always a bad thing, I appreciate the work those devs did.

http://img51.imageshack.us/img51/4641/noobsm.jpg (http://imageshack.us/photo/my-images/51/noobsm.jpg/)

webdev1958
03-21-2012, 10:27 AM
I feel bad for being a noobie now!!!


Don't beat yourself up on it though :)

Everyone was a noobie at some stage :cool:

SeattleMicah
03-21-2012, 07:55 PM
I wont, my project isn't done yet so I must keep going. Onto asynchronously calling my db and inserting the data into my table!!!

SeattleMicah
03-21-2012, 10:35 PM
is this a good place to get started with my next step?

http://www.youtube.com/watch?v=0CMTQtnZ0G0

Old Pedant
03-22-2012, 07:32 AM
is this a good place to get started with my next step?

http://www.youtube.com/watch?v=0CMTQtnZ0G0

Don't ask me. I don't use either jQuery or PHP.

[Actually, I would HATE to learn something off of a video. So that's another thing I don't use. I much prefer reading documentation. But that's me.]



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum