Creating a vertical, dynamic table in Javascript with an array - javascript

Skip right to the bottom if you'd just like to read the questions. The top lot is just context. Not vital but might help.
While working on a table in html I realised something. The code was terrible, repetitive and wasteful. Might as we have been manually adding the array.
<!--
<table border="4px" >
<caption>
Pet Table
</caption>
<tr> // Images
<td>
<script>
display(bat)
</script>;
</td>
<td>
<script>
display(goat)
</script>
</td>
<td>
<script>
display(butterfly)
</script>
</td>
<td>
<script>
display(buzzard)
</script>
</td>
<td>
<script>
display(breezie)
</script>
</td>
<td>
<script>
display(turtle)
</script>
</td>
</tr >
<tr> // Names
<td>
name
</td>
<td>
name
</td>
<td>
name
</td>
<td>
name
</td>
<td>
name
</td>
<td>
name
</td>
</tr>
<tr> //Desc
<td>
desc
</td>
<td>
desc
</td>
<td>
desc
</td>
<td>
desc
</td>
<td>
desc
</td>
<td>
desc
</td>
</tr>
<tr> //Food
<td>
food
</td>
<td>
food
</td>
<td>
food
</td>
<td>
food
</td>
<td>
food
</td>
<td>
food
</td>
</tr>
<tr> //button
<td>
button
</td>
<td>
button
</td>
<td>
button
</td>
<td>
button
</td>
<td>
button
</td>
<td>
button
</td>
</table>
-->
This lead me to spending the morning theorising and experimenting with creating tables dynamically from javaScript instead.
This was the code I was came up with.
In JavaScript (*Edit added pet array)
function pet(species, name, colour, size, food, limb, img) {
this.species = species; //property of a pet
this.name = name; //property of a pet
this.colour = colour; //property of a pet
this.size = size; //property of a pet
this.food = food; //property of a pet
this.limb = limb; //property of a pet
this.img = img; //property of a pet
this.move = move; //a function of a pet defined to the pet
var bat = new pet("fruit bat", "bats", "grey", "small", "apples", "wings", "1", move);
var goat = new pet("goat", "bastard", "off white", "goat-sized", "clothing", "hooves", "2", move);
var butterfly = new pet("butterfly", "flutterby", "rainbow", "petite", "nectar", "wings", "3", move);
var buzzard = new pet("buzzard", "Buzz", "molted black and white", "bigish", "carrion", "wings", "4", move);
var breezie = new pet("pixie", "petty", "blue", "tiny", "souls", "wings", "5", move);
var turtle = new pet("tortoise", "Tank", "Green", "smoothbacked", "lettuce", "legs", "6", move);
var len = pet.length;
function buildTable() {
document.getElementById("work");
//i is a counter, f is a flag
var f = 0;
while (f = 0) {
document.write("<table border='4px'>" + "</br>");
document.write("<caption>Pets Avaliable</caption>" + "</br>");
document.write("<tr>" + "</br>");
for (i = 0; i <= len; i++) {
document.write("<td>" + imgArray[i].outerHTML + "</td>" + "</br>");
}
document.write("</tr>" + "</br>");
document.write("<tr>" + "</br>");
for (i = 0; i <= len; i++) {
document.write("<td>" + pet[i].species + "</td> " + "</br>");
}
document.write("</tr>" + "</br>");
document.write("<tr>" + "</br>");
for (i = 0; i <= len; i++) {
document.write("<td>" + pet[i].name + "</td>" + "</br>");
}
document.write("</tr>" + "</br>");
document.write("<tr>" + "</br>");
for (i = 0; i <= len; i++) {
document.write("<td>" + pet[i].colour + "</td> " + "</br>");
}
document.write("</tr>" + "</br>");
document.write("<tr>" + "</br>");
for (i = 0; i <= len; i++) {
document.write("<td>" + pet[i].size + "</td>" + "</br>");
}
document.write("</tr>" + "</br>");
document.write("<tr>" + "</br>");
for (i = 0; i <= len; i++) {
document.write("<td>" + pet[i].food + "</td>" + "</br>");
}
document.write("</tr>" + "</br>");
document.write("</table>" + "</br>");
f = 1;
}
}
document.getElementById("please");
The HTML
<button id="please" onclick="buildTable(pet)"> Work you blighter </button>
<p id="work"></p>
I just couldn't get it to work. Console was showing no errors yet the button provided no results. After a long while of digging I did manage to come across a button that worked. (I added .innerHTML = "The button is working" to document.getElementById("work")in order to test it.) So the button was alright. Therefore the problem must be in the function itself right? Bloody right. I know it's wrong and I'll try again tomorrow using similar codes to these posts
Dynamically creating a table in javascript /
http://jsfiddle.net/ahEkH/1/
and
Create vertical column table based on Array of Objects
I don't mind working towards an answer nor trial and error but what grinds my garters is that I can't figure out what was the problem. It's good to find out how the code works but I'd like to find out why it works the way it does as well.
Questions
Why can't the console and debugger find any errors yet the page is obviously not working.
How would I label these kinds of problems in the future?What was at fault? The button? The function? Both? Neither? Myself?
I'm planning to make the table in a vertical column format instead of horizontal. Would this be problematic to do? (I'm thinking a few more for loops should do the trick without a fuss)
I'd like to use a pre-constructed array as a source for data(e.g pet[i].size but would this work or would it be better to dis-assemble the array into variables in the function?
if I do need to make variables for all the data would I be able to recycle or reuse a variable if it's inside one of the loops?
In http://jsfiddle.net/ahEkH/1/ why is "tbdy" a child of tab or is appendChild used to assign "tbdy" to tab?
I now know how to go about fixing the dynamic table but I don't know what specifically was wrong in the first place. Please share your knowledge with us.

There are a few things in your code.
while(f=0){ will always evaluate to 0, and hence false. You probably wanted while(f === 0) { (yes, triple ===). This is causing the "I don't see anything in the console" problem, because the code is actually (as you suspected) working albeit not as you expect.
Every one of your loops has for(i = 0; i <= len; i++), where var len = pet.length; You will get an index out of bounds with this, you would want to change to for(i = 0; i < len; i++).
And finally:
You probably don't want to use document.write. The first document.write call will clear the document and replace it with your table. You would be better off with document.createElement and friends to do DOM manipulation (per the jsfiddles you posted). If you go this route, you would be much better off using a library like jQuery, where you could end up with something like this:
//
// Dummy data to make the sample work.
//
var imgArray = [
{outerHTML: '1.jpg'}
, {outerHTML: '2.jpg'}
, {outerHTML: '3.jpg'}
, {outerHTML: '4.jpg'}
];
var pet = [
{species: 'species1', name: 'name1', colour: 'colour1', size: 'size1', food: 'food1'}
, {species: 'species2', name: 'name2', colour: 'colour2', size: 'size2', food: 'food2'}
, {species: 'species3', name: 'name3', colour: 'colour3', size: 'size3', food: 'food3'}
, {species: 'species4', name: 'name4', colour: 'colour4', size: 'size4', food: 'food4'}
];
var attributes = $.map(pet[0], function(n, v) { return v; });
function generateTable(id) {
var $table = $(id);
var $tbody = $('<tbody></tbody>');
$table.append($tbody);
// the images
var $tr = $('<tr />');
$.each(imgArray, function (ignored, image) {
$tr.append($('<td />').html(image.outerHTML));
});
$tbody.append($tr);
$.each(attributes, function (ignored, attribute) {
$tr = $('<tr />');
$.each(pet, function (i, p) {
// i == index, p == pet[i]
$tr.append($('<td />').text(p[attribute]));
});
$tbody.append($tr);
});
}
$(function () {
$('#generateTable').click(function () {
generateTable('#tableHere');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="generateTable">Generate table</button>
<div id="tableHere"></div>
Hope that helps.

Why can't the console and debugger find any errors yet the page is obviously not working.
There are no errors in code, it just doesn't make, what you'd like it to do.
How would I label these kinds of problems in the future?What was at fault? The button? The function? Both? Neither? Myself?
There were a few critical errors, hard to point out one deciding.
I'm planning to make the table in a vertical column format instead of horizontal. Would this be problematic to do? (I'm thinking a few more for loops should do the trick without a fuss)
Making it horizontal may be even easier.
I'd like to use a pre-constructed array as a source for data(e.g pet[i].size but would this work or would it be better to dis-assemble the array into variables in the function?
It is good idea to make a variable for pet[i], if you are going to use it a few times. If you meant making separate tables for size, name etc. - no, there is no need for that.
if I do need to make variables for all the data would I be able to recycle or reuse a variable if it's inside one of the loops?
I'm not sure what do you mean, but probably answer is yes. In javascript variables are local to function, and all loops, ifs etc. inside one function use the same variables.
In http://jsfiddle.net/ahEkH/1/ why is "tbdy" a child of tab or is appendChild used to assign "tbdy" to tab?
tbdy is a child of table element tab, which means that it is inside it.
Ok, now problems with your code:
Code inside while never executes. You have assignment f=0 instead of equality check f==0 (or better f===0) in condition. f=0 has value 0, so it is false. And also, there is no need for loop at all, if you want it to execute exactly once.
document.write is not going to work sensibly while called from onclick. document.write does make sense almost exclusively when called directly in <script> tag, and should be avoided in general.
Your calls to document.getElementById just return object which is then forgotten - they don't have any effect.
You call buildTable with argument pet, but buildTable does not take any arguments (it is not a big problem now, because pet seems to be global variable, but it may be misleading).
You don't declare i as local variable, so it is global. It will work, but in very bug-prone manner.
Putting <br> tag inside <table> does make no sense and is incorrect, and </br> (as you write it) isn't even legal tag.
You might want to put newline character (\n) there, but it is not needed, you don't have to separate html tags.
Your code is very repetitive, with lots of almost identical for loops.
Indent your code, it will make it much nicer to read.
Possible solutions using approach similar to yours (building html piece by piece from strings):
(before using (not recommended), read carefully notes below)
var pet = [
{
species: 'species1',
name: 'name1',
colour: 'colour1',
size: 'size1',
},
{
species: 'species2',
name: 'name2',
colour: 'colour2',
size: 'size2',
},
];
function makeTr(pet, attrName) {
var html = '',
i;
html += "<tr>";
for (i = 0; i < pet.length; ++i) {
html += "<td>" + pet[i][attrName] + "</td>";
}
html += "</tr>";
return html;
}
function buildTable(pet) {
var html='';
html += "<table border='4px'>";
html += "<caption>Pets Avaliable</caption>";
html += makeTr(pet, "species");
html += makeTr(pet, "name");
html += makeTr(pet, "colour");
html += makeTr(pet, "size");
html += "</table>"
document.getElementById("work").innerHTML = html;
}
(jsfiddle)
Note, that it is far from being the best solution, and putting html manually
may be considered bad by principle (althought it may be a bit faster and
could be justified in some cases). In general, creating html tag with
document.createElement seems cleaner and less error-prone way to do that.
Specifically, code above may possibly be subject to XSS attack, because values put into html are not sanitized. Paul's solution is not affected by this problem - note the use of text() method, which escapes html code.

Related

Javascript autocloses HTML tags?

Why do these two functions give different results?
var table1 = document.getElementById("table1");
var table2 = document.getElementById("table2");
var register = [
{att1: 1, att2: 2, att3: 3},
{att1: 4, att2: 5, att3: 6},
{att1: 7, att2: 8, att3: 9}
];
//table1.innerHTML = "";
//table2.innerHTML = "";
function drawTable1() {
for (var i = 0; i < register.length; i++) {
table1.innerHTML += "<tr><td>" + register[i].att1 + "</td><td>" + register[i].att2 + "</td><td>" + register[i].att3 + "</td></tr>";
}
}
function drawTable2() {
for (var i = 0; i < register.length; i++) {
table2.innerHTML += "<tr>";
table2.innerHTML += "<td>" + register[i].att1 + "</td>";
table2.innerHTML += "<td>" + register[i].att2 + "</td>";
table2.innerHTML += "<td>" + register[i].att3 + "</td>";
table2.innerHTML += "</tr>";
}
}
drawTable1();
drawTable2();
table {
display: inline;
}
<body>
<table>
<thead>
<tr>
<th>Att1</th>
<th>Att2</th>
<th>Att3</th>
</tr>
</thead>
<tbody id="table1">
</tbody>
</table>
<table>
<thead>
<tr>
<th>Att1</th>
<th>Att2</th>
<th>Att3</th>
</tr>
</thead>
<tbody id="table2">
</tbody>
</table>
</body>
I'm just beginning with js, and I've noticed this thing. From a logical point of view i see no differences between the two functions, the second has just been broken up to make the code easier to read. It should simply be adding strings to a string, but it seems like at every operation the opened tags get closed by the program, resulting in a multitude of rows.
Why is this? How is this useful?
innerHTML isn't actually a string. It's an interface to the DOM (the elements on the page); reading from it generates a string version of what's currently there, and assigning a value to it modifies the tree.
It's impossible to have an unclosed <tr> element in the DOM -- when you perform an operation like table1.innerHTML += "<tr>", the browser sees the unclosed <tr> tag as invalid HTML and has to repair it by inserting a closing </tr>. When you later access innerHTML to perform another modification, you see the "repaired" version, not the value you initially assigned.
The easiest fix will be to build the entire table as a string, then assign to innerHTML all at once, e.g.
var html = "";
for (...) {
html += "<tr>";
html += "<td>example</td>";
html += "</tr>";
}
table1.innerHTML = html;
You may also want to investigate Javascript DOM methods to create HTML elements (like document.createElement()) as an alternative -- innerHTML is a clumsy interface.
Well the innerHTML content is — as the name implies — HTML and HTML is not just a string. I assume you know that browsers build a DOM out of it. Basically a tree out of nodes that know their tag, attributes, children etc.
Now you need this DOM to render anything. Sure, it is nearly impossible to get invalid html as non-html can just be interpreted as a mere string (which is valid html). However, the browser tries to fullfill the html standard as much as possible. Therefore it also generates missing end tags in order to produce well-formed html. (even when it is not in the html, he will implicitely generate them for the DOM and in some browsers you can see that in the HTML provided in the dev console).
So now you add a random <tr> attribute to your html like this table2.innerHTML += "<tr>". This would produce not-well-formed html. Therefore it should generate the missing end tag. Whether that is done while running the js-code or afterwards when refreshing the DOM, I don't know, but generally it helps generate well-formed HTML.
I'm sure you know how to circumvent that problem, but anyways: Instead of using an temporary string, you might want to look at document.createElement(). This is generally used to generate well-formed html in a non-confusing and safe (as in "something unexpected like above doesn't happen safe") way.

Creating a table with getElementById only shows last instance

I'm using a very simple function to present within a table the name of a person and their age given by the user through a prompt window. The only problem I'm having is that whenever the user adds a second name and age, JS replaces the previous one. It won't add a second row.
http://jsbin.com/jamobifu
JS
function table(){
var numberOfPeople = window.prompt("How many people do you want to add?");
/**/for(var count = 0; count < numberOfPeople; count++){
var name = window.prompt("Type the name of the person");
var age = window.prompt("Type their age");
document.getElementById("tableOfPeople").innerHTML += "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
}
}
HTML
<h1>Making A List</h1>
<p>This program will create a list based on two question which will be asked to you. Type the name of the person and their corresponding age. Output will be presented in a customized table.</p>
<input type="button" value="Create List" onclick="table()" />
<table id="tableOfPeople" style="width: 600px; margin-left: auto; margin-right: auto; margin-top: 50px; background-color: #74a9cb; color: white; border: 1px solid #127bbb"></table>
You shouldn't use innerHTML to modify the contents of a table as it will fail in versions of IE upto and including 9 at least (where innerHTML is readonly for a number of table related elements*). So you should be using DOM insertRow and insertCell methods (or createElement and appendChild, but the insert methods do two steps in one):
var row = document.getElementById("tableOfPeople").insertRow(-1);
var cell = row.insertCell(-1);
cell.appendChild(document.createTextNode(name));
cell = row.insertCell(-1);
cell.appendChild(document.createTextNode(age));
* MSDN::innerHTML property
The innerHTML property is read-only on the col, colGroup, frameSet, html, head, style, table, tBody, tFoot, tHead, title, and tr objects.
You Forgot += instead =
function table(){
var numberOfPeople = window.prompt("How many people do you want to add?");
/**/for(var count = 0; count < numberOfPeople; count++){
var name = window.prompt("Type the name of the person");
var age = window.prompt("Type their age");
document.getElementById("tableOfPeople").innerHTML += "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
}
}
Your problem is right here. Every time the user adds a new name you are replacing the old information instead of adding to it. Any time the innerHTML method is called on an element it will delete the old HTML information inside of the element.
document.getElementById("tableOfPeople").innerHTML = "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
What you could do is store this information to a variable and then add that with the new information.
Something along the lines of:
var information = document.getElementById("tableOfPeople").innerHTML;
document.getElementById("tableOfPeople").innerHTML = information + "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
This is because you are replacing the innerHTML with the new table row, not adding to it. You can solve this pretty easily by replacing
document.getElementById("tableOfPeople").innerHTML = "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
With:
document.getElementById("tableOfPeople").innerHTML += "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
The += operator adds to the existing value. For example, the following code:
a = 4;
a += 2;
alert(a); //alerts 6
As #cookiemonster pointed out, there are numerous caveats to this approach. The cost of using .innerHTML to alter the DOM is high and destructive. It requires the DOM to be parsed into a string, the string altered, then parsed back into the DOM. This process destroys any event listeners or other information you may have had on the elements.
It will also make things more difficult as you wish to extend the functionality of the code, to add things like the ability to delete rows.
#RobG has presented a much better solution, and as he points out .innerHTML can fail in various versions of IE.

jquery adding columns based on database records

I have an sqlite table with these columns:
| date | weight | bmi | mood | etc.
I want a table on my html page to display like this on the html page:
<table>
<caption></caption>
<thead>
<tr>
<td>(empty cell over row headings)</td>
Additional tH's as needed (this is where each date entry goes)
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Weight</th>
additional tD's as needed (this is where each weight entry goes matched with date in column heading)
</tr>
<tr>
<th scope="row">BMI</th>
additional tD's as needed (same as above)
</tr>
</tbody>
</table>
so basically I'm flipping the rows and columns for display purposes. This is all so I can graph the table using jQuery Visualize plugin that goes out as the date progresses. As you can imagine, over time more entries will be made adding to the columns of the display table. Here is what I have been messing around with so far (not including the graphing scripts ). I've gotten myself totally confused and now I'm just a mess...
Any suggestions would be a big help. I think I'm running into problems when trying to insert data into a table that's also trying to insert itself. I'm probably going about this wrong I bet.
Thanks
Mike
function homeSuccess(tx, results) {
// Gets initial count of records in table...
var entries = results.rows.length;
// Iterates over all the existing records...
for (var i = 0; i < entries; ++i) {
// The following element id's can be found in the div's within the table below, see element.innerHTML line...
var element = document.getElementById('colDate');
element.innerHTML += '<th scope="col">' + results.rows.item(i).timeStamp + '</th>';
var element2 = document.getElementById('tdWeight');
element2.innerHTML += '<td>' + results.rows.item(i).weight + '</td>';
var element3 = document.getElementById('tdBmi');
element3.innerHTML += '<td>' + results.rows.item(i).bmi + '</td>';
};
// 'screenView2 is a placeholder on the main html page...
var element = document.getElementById('screenView2');
element.innerHTML = '<br /><br /><h1>Data:</h1><br />Number of entries: ' + entries + '<br />' + '<table><caption>Mikes Health</caption><thead><tr><td></td><div id="colDate"></div></tr></thead><tbody><tr><th scope="row">Weight</th><div id="colWeight"></div></tr><tr><th scope="row">BMI</th><div id="colBmi"></div></tr></tbody></table>';
// This section is just a test trying to plug in static elements prior to trying database data... When using this section I had the iteration section commented out.
var element2 = document.getElementById('colDate');
element2.innerHTML = '<th scope="col">4-1-13</th>';
var element3 = document.getElementById('colWeight');
element3.innerHTML = '<td scope="col">123</td>';
var element4 = document.getElementById('colBmi');
element4.innerHTML = '<td scope="col">321</td>';
}
function homeQuery(tx) {
console.log("entering homeQuery");
tx.executeSql('SELECT * FROM HEALTHGRAPH', [], homeSuccess, onSqlError);
console.log("leaving homeQuery");
}
// Function that is called on initial page load
function homeDBopen() {
console.log("opening db for home data");
theDB = window.openDatabase("hgDB", "1.0", "HealthGraph", 3 * 1024 * 1024);
theDB.transaction(homeQuery, onTxError, onTxSuccess);
console.log("leaving homeDBopen");
}
Thought for sure someone would have answered this question as it seems like an issue lots of people must run into. A little discouraging. Anyway, I found an answer that I can adapt to my own project here:
http://msdn.microsoft.com/en-us/library/ie/ms532998(v=vs.85).aspx
// Insert cells into the header row.
for (i=0; i<heading.length; i++)
{
oCell = oRow.insertCell(-1);... etc.

Javascript variable as html tag name

Here is my code..
<!DOCTYPE html>
<html>
<script>
function genbox()
{
var i;
var myarray = new Array();
myarray[0] = "name";
myarray[1] = "dob";
myarray[2] = "email";
for (i=0;i<myarray.length;i++)
{
document.write('<input name="' + myarray[i] + '"/>');
}
}
</script>
<body>
<input type="button" value="create" onclick="genbox();">
</body>
</html>
Old:I want the textbox name as the values of the array such as name, dob etc. but all i'm getting is 3 textboxes with the same name "myarray[i]". Please help me.
Okay, Here we go, I'm pretty new to js. After clicking the button it creates 3 textboxes, but, the button disappears, What should I do to keep the button alive???
try this line in the loop instead:
document.write('<input name="' + myarray[i] + '"/>');
Working jsfiddle is here.
You can't insert JavaScript variables inside a string and expect the interpreter to extract its value (as some languages do, like PHP). Build your string using concatenation instead:
"<input name='" + myArray[i] + "'/>"
You should go through some basic tutorials about javascript, try http://www.codecademy.com/
Here's the code, however you shouldn't add html with document.write, there are other, better methods to do it.
var i,
myarray = ["name", "dob", "email"];
for (i = 0, ilen = myarray.length; i < ilen; i++) {
document.write('<input name="' + myarray[i] + '"/>');
}

How do I get this widget to display using the appendTo() function, in JQuery?

I have this code & I've tired using JQuery's appendTo() function to get this widget to display...there is something I'm missing but I'm having trouble pin-pointing it.
Here is the original code, see below:
var theText = new Array();
theText[0] = "David Footitt is absolutely delighted with them and the service he received.<br /><br />Regtransfers are definitely the first port of call whenever I or my colleagues are looking for a special number plate, he said.";
theText[1] = "What was Prakash Patel's experience with Regtransfers?<br /><br />Great service, always keeping us up to date with related plates, transfers done very easily and value for money.";
theText[2] = "4 MBE is one the best investments that I have made in recent years.<br /><br />Thanks to Regtransfers for making it such a simple and straightforward process. It's definitely got me thinking about others for the business.";
var links = new Array();
links[0] = 'http://www.regtransfers.co.uk/number-plates-stories/new51.asp';
links[1] = 'http://www.regtransfers.co.uk/number-plates-stories/oo08cty.asp';
links[2] = 'http://www.regtransfers.co.uk/main/stories/4mbe.asp';
var title = new Array();
title[0] = '<strong>David Footitt</strong><br />(News Transport Ltd)<br />NEW 51';
title[1] = '<strong>Prakash Patel</strong><br />(City Inter-Rent)<br />OO08 CTY';
title[2] = '<strong>Sandeep Patel</strong><br />(Ambe Medical Group)<br />4 MBE';
var images = new Array();
images[0] = '/images_new/rotatingTestimonials/new51.jpg';
images[1] = '/images_new/rotatingTestimonials/oo08cty.jpg';
images[2] = '/images_new/rotatingTestimonials/4mbe.jpg';
var j = 0
var p = theText.length;
var whichImage = Math.round(Math.random()*(p-1));
document.write('<div style="padding:3px; border:1px solid #CCC;"><div style="background-image:url(/images_new/backgrounds/grey_gradient.jpg); background-repeat:repeat-x; text-align:center; font-weight:bold; font-size:90%; padding:5px;">Satisfied Customer</div><p align="center" style="font-size:11px;">' + title[whichImage] + '</p><p align="center" style="font-size:11px;"><img src="' + images[whichImage] + '" alt="Customer Testimonials" style="width:140px" /></p><p align="left" style="font-size:11px;">' + theText[whichImage] + '</p><p align="right" style="font-size:11px;">read more ...</p></div>');
I thought if I change the last line to:
$('<div...long html string with the other variables').appendTo($('#rotate-testimonials'));
it might work. Can anyone tell me where I'm going wrong??
Any help is Greatly Appreciated, Thanks
Fundamentally, it works, but I suspect you wanted to replace the rotate-testimonials content rather than appending (adding) to it. So the last line would be:
$('#rotate-testimonials').html(...long string...);
Live example
Edit: You've said that what's going wrong on your end is that nothing shows up in the DIV#rotate-testimonials. You should have been seeing something, even with your original code, so here are some things to check:
Are you running your code before the div#rotate-testimonials exists in the DOM? E.g., is the script above the div and not wrapped in a ready handler or similar? This is an easy-to-make mistake. The div has to exist before you can write to it, and script is run immediately. In my example above, note that everything is wrapped in a jQuery(function($) { ... }); structure, which isn't called until the DOM is ready to be manipulated. You can do it that way, or just put your script at the very end of the page, just before your </body> tag.
Do you really have a div with id="rotate-testimonials"? E.g., no typos or similar, it's an id not a name, etc.
Do you have only one element or other global object with that name? (Easy way to check: Change the name to "fluglehorn" both in the id="..." in the markup and in the script. If it starts working, that means you have something else also called rotate-testimonials kicking around somewhere. Of course, this assumes you don't have anything called fluglehorn lying around...
If it's none of those things, I'm out of ideas, but hopefully comparing what you have with the working version above will help.
Off-topic: That said, a bit of refactoring can help make it easier to add entries to the testimonials, etc. Rather than parallel arrays, I'd use an array of objects, with a property for each of the bits of information (text, title, link, image). Also, you can use array and object literal notation (rather than new Array(); and then a bunch of assignments.
Here's a version that just changes to array literal notation:
var theText = [
"David Footitt is absolutely delighted with them and the service he received.<br /><br />Regtransfers are definitely the first port of call whenever I or my colleagues are looking for a special number plate, he said.",
"What was Prakash Patel's experience with Regtransfers?<br /><br />Great service, always keeping us up to date with related plates, transfers done very easily and value for money.",
"4 MBE is one the best investments that I have made in recent years.<br /><br />Thanks to Regtransfers for making it such a simple and straightforward process. It's definitely got me thinking about others for the business."
];
var links = [
'http://www.regtransfers.co.uk/number-plates-stories/new51.asp',
'http://www.regtransfers.co.uk/number-plates-stories/oo08cty.asp',
'http://www.regtransfers.co.uk/main/stories/4mbe.asp'
];
var title = [
'<strong>David Footitt</strong><br />(News Transport Ltd)<br />NEW 51',
'<strong>Prakash Patel</strong><br />(City Inter-Rent)<br />OO08 CTY',
'<strong>Sandeep Patel</strong><br />(Ambe Medical Group)<br />4 MBE'
];
var images = [
'/images_new/rotatingTestimonials/new51.jpg',
'/images_new/rotatingTestimonials/oo08cty.jpg',
'/images_new/rotatingTestimonials/4mbe.jpg'
];
var j = 0
var p = theText.length;
var whichImage = Math.round(Math.random()*(p-1));
$('#rotate-testimonials').html(
'<div style="padding:3px; border:1px solid #CCC;"><div style="background-image:url(/images_new/backgrounds/grey_gradient.jpg); background-repeat:repeat-x; text-align:center; font-weight:bold; font-size:90%; padding:5px;">Satisfied Customer</div><p align="center" style="font-size:11px;">' + title[whichImage] + '</p><p align="center" style="font-size:11px;"><img src="' + images[whichImage] + '" alt="Customer Testimonials" style="width:140px" /></p><p align="left" style="font-size:11px;">' + theText[whichImage] + '</p><p align="right" style="font-size:11px;">read more ...</p></div>');
Live copy
And here's a minimally-refactored version that uses an array of objects instead:
var entries = [
{ text: "David Footitt is absolutely delighted with them " +
"and the service he received.<br /><br />Regtransfers " +
"are definitely the first port of call whenever I or " +
"my colleagues are looking for a special number plate, he said.",
link: "http://www.regtransfers.co.uk/number-plates-stories/new51.asp",
title: "<strong>David Footitt</strong><br />(News Transport Ltd)<br />NEW 51",
image: "/images_new/rotatingTestimonials/new51.jpg"
},
{ text: "What was Prakash Patel's experience with Regtransfers?<br />" +
"<br />Great service, always keeping us up to date with related " +
"plates, transfers done very easily and value for money.",
link: "http://www.regtransfers.co.uk/number-plates-stories/oo08cty.asp",
title: "<strong>Prakash Patel</strong><br />(City Inter-Rent)<br />OO08 CTY",
image: "/images_new/rotatingTestimonials/oo08cty.jpg"
},
{ text: "4 MBE is one the best investments that I have made in recent " +
"years.<br /><br />Thanks to Regtransfers for making it such a " +
"simple and straightforward process. It's definitely got me " +
"thinking about others for the business.",
link: "http://www.regtransfers.co.uk/main/stories/4mbe.asp",
title: "<strong>Sandeep Patel</strong><br />(Ambe Medical Group)<br />4 MBE",
image: "/images_new/rotatingTestimonials/4mbe.jpg"
}
];
var j = 0
var p = entries.length;
var whichImage = Math.round(Math.random()*(p-1));
$('#rotate-testimonials').html(
'<div style="padding:3px; border:1px solid #CCC;"><div style="background-image:url(/images_new/backgrounds/grey_gradient.jpg); background-repeat:repeat-x; text-align:center; font-weight:bold; font-size:90%; padding:5px;">Satisfied Customer</div><p align="center" style="font-size:11px;">' + entries[whichImage].title + '</p><p align="center" style="font-size:11px;"><img src="' + entries[whichImage].image + '" alt="Customer Testimonials" style="width:140px" /></p><p align="left" style="font-size:11px;">' + entries[whichImage].text + '</p><p align="right" style="font-size:11px;">read more ...</p></div>');
Live copy
You can go even further than that (and certainly a stylesheet would help that massive string at the end), but you get the idea.
jQuery also has the basic .append() method, which should work great and reads a bit easier.
$('#rotate-testimonials').append('...')
You should be using a selector and not the text. Put in the selector for your DIV with lots of text in place of the div content itself and you should be fine
<div id='theDiveID'>long html string with the other variables</div>
$('#theDivID').appendTo('#rotate-testimonials');

Categories