I am adding buttons based on an array. The problem I am having is that every time I add another name to the array, it prints out all the buttons not just the one I added. I am wondering how would I erase all the old buttons before I add the array of buttons.
Here is my code
socket.on('usernames', function(data){
console.log(data);
for(i=0; i <data.length; i++){
// html += data[i] + "<br/>";
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}
// $users.html(html);
});
Below is an image. Test is the name of the first button and every time I add a new button it prints the entire array again. Is there a way to delete the old buttons?
Use the empty() method before you loop:
socket.on('usernames', function(data){
var $contentWrap = $("#contentWrap").empty();
for (i = 0; i < data.length; i++) {
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($contentWrap);
}
});
Also note that you can improve performance and tidy the code by creating a single HTML string and setting the html() property to only require one DOM call. Try this:
socket.on('usernames', function(data){
var html = data.map(function(value) {
return '<input type="button" value="' + value + '"/></br>'
}).join('');
$('#contentWrap').html(html);
});
You can call .empty() on the parent element before appending the elements again.
$("#contentWrap").empty();
for(i=0; i <data.length; i++){
// html += data[i] + "<br/>";
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}
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.
I have the table data which is displyaed like below, where Dispute Number has a link.
I have generated the html code using the function below
getMessage(result){
for (var j = 0; j < result.invocationResult.resultSet.length; j++) {
var tmp = "<tr>";
var resSet = result.invocationResult.resultSet[j];
for(res in resSet){
if(res=="DISP_NUMBER")
var ab = resSet.DISP_NUMBER;
tmp += "<td><a href="+"#"+" data-role="+" button"+" id="+" button-mainpage" +" onclick="+ " changeToSomePage("+ab+");>"+ab +"</a></td>";
$("#mytable").append(tmp+"</tr>");
When the user clicks on the dispute number link, the below js function gets called.
I am passing the dispute number with the variable 'ab'. When i alert this value in the function changeToSomePage(ab),
it works sometimes, sometimes it giving incorrect number.
function changeToSomePage(ab) {
alert(ab);
$('#pagePort').load("pages/disputedetails.html");
}
Do you see anything wrong with the above code ? Is this the right apporach to retrieve the value from a link & send it to a JS function when clicked ??
Thanks..Johnson
It looks like ab is a string. You need to wrap it with quotes.
"<td><a href="+"#"+" data-role="+" button"+" id="+" button-mainpage" +" onclick="+ " changeToSomePage(\""+ab+"\");>"+ab +"</a></td>";
Of course inline handlers are not the best way. You can use event delegation instead: bind single onclick handler on the table itself.
$('#mytable').on('click', '.change-to-some-page', function() {
var num = $(this).data('num');
});
And when generating rows.
tmp += '<td><a href="#" data-role="button" class="change-to-some-page" ' +
'data-num="' + ab + '">' +ab +'</a></td>';
rewrite this
"<td><a href="+"#"+" data-role="+" button"+" id="+" button-mainpage" +" onclick="+ " changeToSomePage("+ab+");>"+ab +"</a></td>"
using double and single quotes - much easier to read. and create unique ids ith the j value
"<td><a href='#' data-role='button' id='button-mainpage-" + j + "' onclick=' changeToSomePage("+ab+");'>"+ab +"</a></td>"
I've a Javascript with Jquery.
http://jsfiddle.net/P5gD7/3/
var libelle = 'tes\'te';
var id = 1;
var toAdd = "<input type='text' name='choix[" + id + "]' value='" + libelle + "' />";
$("#test").append(toAdd);
The problem is when I've a quote in "libelle" variable (i've escaped this quote), when I use append, Jquery put only tes in the "value" attribute.
I have to do with simple quote.
For info an alert(toAdd) return me the entire input with no errors.
Any ideas ?
Thanks
If you use jQuery to create the element for you through properties instead of string manipulation you can avoid these kind of problems:
var libelle = 'tes\'te';
var id = 1;
$('<input />', {
type: 'text',
name: 'choix[' + id + ']',
value: libelle
}).appendTo('#test');
Example fiddle
One approach here is to create the element, then set the value on that element. These can be chained together something like:
var libelle = "tes'te";
var id = 1;
var toAdd = "<input type='text' name='choix[" + id + "]' />";
// create the element, show and finally set the value (.val)
$(toAdd).appendTo("#test").val(libelle);
See The Fiddle Here
I need to use Javascript to generate a table from user input in a prompt window.
This is for homework and we haven't covered things like jQuery or function scripting, all we've done is basic calculation scripts and the teacher has asked that we use a similar method to what we've been taught to solve the issue.
I have Googled and tried to solve it from what I found, but I don't particularly want to use methods we haven't been taught just yet, and the one method I found that does work is far more advanced than what we've done in class. And I just know that if I ask the teacher he won't be very helpful.
This is what I've got so far, and it generates a list of the input times table up to 10, but I need that data to end up in a table, all I need to know is where do I need the document.write tags to generate the numbers into a table?
Can it be done with some simple commands? Or is it more advanced than what we've been taught so far?
<html>
<body bgcolor=#66ccff text=#ff6600>
<script type="text/javascript">
var number = prompt("Please enter a number:");
for (i=1; i <= 10; i++)
{document.write( number + " x " + i + " = " + i*number + "<br>");};
</script>
</body>
</html>
What about this way:
<html>
<body bgcolor="#66ccff" text="#ff6600">
<script type="text/javascript">
var number = prompt("Please enter a number:");
document.write('<table border="1">');
for (i=1; i <= number; i++) {
document.write('<tr><td>' + number + " x " + i + "</td><td>=</td><td>" + i*number + "</td></tr>");
};
document.write('</table>');
</script>
</body>
</html>
I just assigned 2 to undefined number so at first run you don't have the error
<script type="text/javascript">
var number = prompt("Please enter a number:");
if(number == undefined)
number =2;
for (i=1; i <= 10; i++)
{document.write( number + " x " + i + " = " + i*number + "<br>");};
</script>
jsbin link is here: https://jsbin.com/puvitinaxi/edit?html,output