What I am trying to do is retrieve the information passed from a previous page through and display this within a table on another page.
I have currently got the following code:
PAGE NAME: EMBELLISHMENT
<script>
var embellishmentlist_var = embellishment;
var embellishment_explode = embellishmentlist_var.split("#");
for(var i = 1; i < embellishment_explode.length; i++)
{
var embellishment_explode_singleinfo = embellishment_explode.split("_");
//var table = '<tr><td>' + embellishment_explode[3] + '</td><td>' + data[7] + '</td><td>' + data[1] + '</td><td>' + data[2] + '</td><td>' + data[4] + '</td><td>' + data[5] + '</td>' + data1 + '<td>' + data[9] + '</td></tr>';
var table = '<tr><td></td></tr>';
$('#tableshow > tr').append( table );
//alert(embellishment_explode[4]);
}
}
</script>
<html>
<table>
<tr id="tableshow">
</tr>
</table>
The foreach can loop round a maximum of 6 times which I hope will create 6 rows within the table however this does not seem to be working. I currently have similar code to the above on another page however the HTML is slightly different. On that page the HTML looks like the following:
PAGE NAME: INFO
<table id="items_table">
<th>1</th>
<th>2</th>
///etc
</table>
The Javascript on that page insert rows into the table. This all works.
Therefore the only difference between the two pages is that on the EMBELLISHMENT page I want to create table rows within a table whereas on the INFO page I am creating the complete table.
Could I please have some assistance even if it is just to say it isn't possible.
You're trying to append table rows to a table row. That's not possible. You could only add rows to a table
HTML
<table id="tableshow"></table>
JS
for(var i = 0; i <= 6; i++){
$('#tableshow').append('<tr><td></td></tr>');
}
Related
this is for a web app that will take in a survey I am using firebase. What I need help in is when the app is exporting the data into a table it grabs the data but won't is able to push it to the table any help would be appreciated. Since the HTML code is a long one I will only put the table portion:
the table portion of the HTML file
<div id = "table">
<pre id = "snap-test"></pre>
<table id ="File-Table" class="table">
<thead>
<tr>
'<td><button onclick = "DeleteTabele()" id = "Delete-btn">Delete File</button></td>'
</tr>
</thead>
<button onclick ="Return()" id= "Log-btn" type="submit" class="btn btn-">Add a new File</button>
</table>
</div>
the Table.js file
var table = document.getElementById("File-Table");
const file = $("#File").val();
var requests = [];
function Export(){
//calls the file id in the HTML element
$("#Survey-Page").hide();
$("#File-Table").show();
$("#Log-btn").show();
var result = [];
//calls the database from the firebase known as users then using a function we nest a snapshot in it for later
firebase.database().ref('/users/').once('value').then(function(snapshot){
//if snapshot is empty then the window will alert
if (snapshot.val() == null){
alert("Does not exist");
}
// if the snapshot is full then it will genereate a table based on the snapshot value of the database
else {
console.log(snapshot.val());
let result = snapshot.val()
for(let k in result){
this.requests.push({
id: k,
value: result[k]
});
}
var MyTable = '<tr>' +
'<td>' + snapshot.val().txtName +'</td>' +
'<td>' + snapshot.val().txtEmail +'</td>' +
'<td>' + snapshot.val().FileName + '</th>' +
'<td><button id = "Email-btn">Send Survey</button></td>' +
'<td><button onclick = "DeleteTabele()" id = "Delete-btn">Delete File</button></td>' +
'</tr>';
MyTable += "</tr></table>";
table.innerHTML = MyTable;
}
console.log(snapshot.val());
});
From the code you have published, the more probable cause is that your reference is referencing a node of multiple users and not a specific user.
firebase.database().ref('/users/')
To confirm this assumption we need to see your database structure. Can you edit you post?
However, let's imagine this assumption is correct. Then you have two solutions:
If you want to display the value of ONE user which is under the users node, you have to change the reference and point to this user, e.g.:
firebase.database().ref('/users/' + userID)
Then the rest of the code will work normally
If you want to display in your table the entire list of users (one by row) you have to loop over the results of the query, as follow:
firebase.database().ref('/so').once('value').then(function(snapshot){
var MyTable;
snapshot.forEach(function(childSnapshot) {
MyTable += '<tr>' +
'<td>' + childSnapshot.val().txtName +'</td>' +
'<td>' + childSnapshot.val().txtEmail +'</td>' +
// ...
'<td><button id = "Email-btn">Send Survey</button></td>' +
'<td><button onclick = "DeleteTabele()" id = "Delete-btn">Delete File</button></td>' +
'</tr>';
});
table.innerHTML = MyTable;
});
See the doc here: https://firebase.google.com/docs/database/web/lists-of-data#listen_for_value_events
In addition, if I may, you could have a look at this SO post: HTML : draw table using innerHTML which shows some best practices for writing rows of a table in "simple" JavaScript.
I have to show dynamically checkboxes in a HTML page and get their value from database.
The trick I used is to create the whole table HTML in java and then using AJAX I do this
var div = document.getElementByID("div").innerHTML = htmlCode;
but issue is
in htmlCode variable, the html is like
<table width="100%">
<tr>
<td width="50%">......
but when I check div.innerHTML it shows like
<TABLE width="100%">
<TBODY>
<TR>
<TD width="50%">
<?xml:namespace prefix = ....
Why they become uppercase and why is xml:namaesapce prefix added ?
This causes issue as table is not properly displayed.
Is there any other better way to do this without using innerHTML ?
The code for generation of table is
String html = "<table width=\"100%\">";
for (Iterator it = lookupList.iterator (); it.hasNext ();)
{
HashTree lookupElement = (HashTree) it.next ();
String code = lookupElement.getChildTagValue ("CODE");
String text = lookupElement.getChildTagValue ("TEXT");
String labelText = "";
if(indexLookupElement == 0)
labelText = "First Checkbox label";
html = html + "<tr><td width=\"50%\" >" +
+
"<input type=\"checkbox\" id=\"item" + code + "\" />" +
"<html:label " +
"id=\"_Description\"" +
"name=\"_Description\"" +
">" + text +
"</html:label>" +
"<td width=\"50%\" >" +
"</td></tr>";
indexLookupElement += 1;
}
html = html + "</table>";
Thanks,
Aiden
It's not a best practice to create the HTML code server-side. If you are sure you'll have the table in your document it's better to make it part of the structure of the document and feed only the variables from your Java code. Even if the table is conditional you may consider hide/unhide it with a variable. I believe this approach will solve your problem if the HTML code of your webpage is correct.
Update
Test it like this:
html = html + "<tr><td width=\"50%\"><input type=\"checkbox\" id=\"item" + code + "\" /><label id=\"_Description\" name=\"_Description\">" + text + "</label></td><td width=\"50%\"></td></tr>";
In your code you have missing TD closing tag and I made some changes. See if this will fix your problem.
I am trying to create a HTML table like the following dynamically using jQuery:
<table id='providersFormElementsTable'>
<tr>
<td>Nickname</td>
<td><input type="text" id="nickname" name="nickname"></td>
</tr>
<tr>
<td>CA Number</td>
<td><input type="text" id="account" name="account"></td>
</tr>
</table>
This is my actual table :
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
This is the method which will create tr and td elements taking id and labelText:
function createFormElement(id, labelText) {
// create a new textInputBox button using supplied parameters
var textInputBox = $('<input />').attr({
type: "text", id: id, name: id
});
// create a new textInputBox using supplied parameters
var inputTypeLable = $('<label />').append(textInputBox).append(labelText);
// append the new radio button and label
$('#providersFormElementsTable').append(inputTypeLable).append('<br />');
}
I also have a value which will be shown as tool tip.
Please help me to create a table dynamically with tool tip and tr td.
EDIT:
I have almost done with the following code:
function createProviderFormFields(id, labelText,tooltip,regex) {
var tr = '<tr>' ;
// create a new textInputBox
var textInputBox = $('<input />').attr({
type: "text",
id: id, name: id,
title: tooltip
});
// create a new Label Text
tr += '<td>' + labelText + '</td>';
tr += '<td>' + textInputBox + '</td>';
tr +='</tr>';
return tr;
}
Here label is coming properly and the input box is not coming and it shows [object Object] where the text box has to come...
When I printed the textInputBox using console.log, I get the following:
[input#nickname, constructor: function, init: function, selector: "", jquery: "1.7.2", size: function…]
What could be the issue?
Thanks to #theghostofc who showed me path... :)
You may use two options:
createElement
InnerHTML
Create Element is the fastest way (check here.):
$(document.createElement('table'));
InnerHTML is another popular approach:
$("#foo").append("<div>hello world</div>"); // Check similar for table too.
Check a real example on How to create a new table with rows using jQuery and wrap it inside div.
There may be other approaches as well. Please use this as a starting point and not as a copy-paste solution.
Edit:
Check Dynamic creation of table with DOM
Edit 2:
IMHO, you are mixing object and inner HTML. Let's try with a pure inner html approach:
function createProviderFormFields(id, labelText, tooltip, regex) {
var tr = '<tr>' ;
// create a new textInputBox
var textInputBox = '<input type="text" id="' + id + '" name="' + id + '" title="' + tooltip + '" />';
// create a new Label Text
tr += '<td>' + labelText + '</td>';
tr += '<td>' + textInputBox + '</td>';
tr +='</tr>';
return tr;
}
An example with a little less stringified html:
var container = $('#my-container'),
table = $('<table>');
users.forEach(function(user) {
var tr = $('<tr>');
['ID', 'Name', 'Address'].forEach(function(attr) {
tr.append('<td>' + user[attr] + '</td>');
});
table.append(tr);
});
container.append(table);
Here is a full example of what you are looking for:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='nickname' name='nickname'></td></tr><tr><td>CA Number</td><td><input type='text' id='account' name='account'></td></tr>");
});
</script>
</head>
<body>
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
</body>
I understand you want to create stuff dynamically. That does not mean you have to actually construct DOM elements to do it. You can just make use of html to achieve what you want .
Look at the code below :
HTML:
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'></table>
JS :
createFormElement("Nickname","nickname")
function createFormElement(labelText, id) {
$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='"+id+"' name='nickname'></td><lable id='"+labelText+"'></lable></td></tr>");
$('#providersFormElementsTable').append('<br />');
}
This one does what you want dynamically, it just needs the id and labelText to make it work, which actually must be the only dynamic variables as only they will be changing. Your DOM structure will always remain the same .
WORKING DEMO:
Moreover, when you use the process you mentioned in your post you get only [object Object]. That is because when you call createProviderFormFields , it is a function call and hence it's returning an object for you. You will not be seeing the text box as it needs to be added . For that you need to strip individual content form the object, then construct the html from it.
It's much easier to construct just the html and change the id s of the label and input according to your needs.
FOR EXAMPLE YOU HAVE RECIEVED JASON DATA FROM SERVER.
var obj = JSON.parse(msg);
var tableString ="<table id='tbla'>";
tableString +="<th><td>Name<td>City<td>Birthday</th>";
for (var i=0; i<obj.length; i++){
//alert(obj[i].name);
tableString +=gg_stringformat("<tr><td>{0}<td>{1}<td>{2}</tr>",obj[i].name, obj[i].age, obj[i].birthday);
}
tableString +="</table>";
alert(tableString);
$('#divb').html(tableString);
HERE IS THE CODE FOR gg_stringformat
function gg_stringformat() {
var argcount = arguments.length,
string,
i;
if (!argcount) {
return "";
}
if (argcount === 1) {
return arguments[0];
}
string = arguments[0];
for (i = 1; i < argcount; i++) {
string = string.replace(new RegExp('\\{' + (i - 1) + '}', 'gi'), arguments[i]);
}
return string;
}
I am generating a dynamic table on click of a button as below -
$('.addRowButton').click(function () {
++counter;
var index=counter-1;
var newRowHtml =
'<tr>' +
'<td>' + counter +
'</td>' +
'<td><input name="b2bProductList[' + index+ '].productId" class="variant b2bTableInput" /></td>' +
'<td align="center"><span id="pvDetails" class="pvDetails"></span></td>' +
'<td><div class="img48" style="vertical-align: top;"><img src=""></td>'+
'<td><input name="b2bProductList[' + index + '].quantity" class="qty b2bTableInput"/></td>' +
'<td align="center"><span id="mrp" class="mrp"/></td>' +
'<td align="center"><input id="totalPrice" readonly="readonly" class="totalPrice b2bTableInput" type="text"></td>' +
'</tr>';
$('#poTable').append(newRowHtml);
But I want to handle a particular column my self - kind of override it. I have to display an image and have to use some attributes in this column it which I can not put in the above code. How should I override it. If I am going to declare any tr or td in my table in the main <table></table> they are taking up extra row statically. Is there any particular way to handle a particular column while adding the rows dynamically?
EDIT - I have to set the source of the image, the source string of which I am fetching through an async call on the focusout of my Id textbox. Now can not set the source in the row generation time, so I will have to handle each column at a time giving src after I have fetched it. The column is mentioned in my code
'<td><div class="img48" style="vertical-align: top;"><img src=""></td>'+
Now I have to set the src. I hope this tells my problem clearly.
You could use
$('#myTable tr td::nth-child('+columnIndex+')')
if you know the index of the column or you could give that specific td a unique class
newRowHtml ='<tr>' + '<td class="someClass"></td> ... etc
and select that class:
$('.someClass').each(function(){
// Some other code
});
Alternatively you could add the rows like so:
var $row = $('<tr></tr>');
var $id = $('<td></td>').html(id);
var $someOtherfield = $('<td></td>').html(someOtherData);
$('#myTable').append($row.append($id).append($someOtherfield));
then use the variable $someOtherfield to access it and work on it.
$someOtherfield.find('img').attr('src' , yourSource);
The simplest to select the cells of a specific column, if you have no fancy colspan, is to use :nth-child() :
$('#mytable td:nth-child('+columnIndex+')')
var tds= $('#poTable').find("td:first");
will give you the first column.
and to iterate over the elements
tds.each(function(index){
//do your stuff here..
});
hope this helps..
I got this json object which its structure similar to this:
vendor have name, phone, fax, contacts
contacts have firstName, lastName, title, phone, email
I have created the first level in the table, but i didn't how to create the second nested level
function getData(vType) {
$.getJSON('/LocalApp/VendorController', {
vendorType : vType,
time : "2pm"
}, function(vendorsJson) {
$('#vendors').find("tr:gt(0)").remove();
var vendorTable = $('#vendors');
$.each(vendorsJson, function(index, vendor) {
$('<tr>').appendTo(vendorTable).append(
$('<td>').text(vendor.name)).append(
$('<td>').text(vendor.phone)).append(
$('<td>').text(vendor.fax)).append(
'<table class="contactTable"><tr><th>First Name</th><th>Last Name</th><th>Title</th><th>Phone</th><th>E-Mail</th></tr></table>');
});
});
}
So how can i add vendor.contacts as a nested table in jQuery code?
i know my code is not clean, jquery is confusing to me compared to Java
Not sure if you want the table in a cell of the vendor or not, but try something like this...
var contactTableHtml = '<table class="contactTable"><tr><th>First Name</th><th>Last Name</th><th>Title</th><th>Phone</th><th>E-Mail</th></tr></table>';
var vendorTableContent = $.map(vendorsJson,function (index, vendor) {
var contactTableContentHtml = $.map(vendor.contacts,function (index, contact) {
return "<tr><td>" + contact.firstName + "</td><td>" + contact.lastName + "</td><td>" + contact.title + "</td><td>" + contact.phone + "</td><td>" + contact.email + "</td></tr>";
}).join("");
return '<tr>' +
'<td>' + vendor.name + '</td>' +
'<td>' + vendor.phone + '</td>' +
'<td>' + vendor.fax + '</td>' +
'<td>' + contactTableHtml + contactTableContentHtml + '</td>' +
'</tr>';
}).join("");
vendorTable.append(vendorTableContent);
First I create a subtable as a string and then add it to the main table. I also suggest to create one big html string and add it once to the DOM. This is a lot quicker then calling $('...') everytime.
PS. Haven't been able to test it, but let me know if you get an error.
Unless you're very constrained for how much you can send with the page (that is, every single K of data counts against you), I don't think jQuery is a good fit for this kind of thing.
I think of JSON + something => HTML as templating, so I usually use a JavaScript templating tool like Handlebars to do that kind of thing. It's a more natural fit. Plus you can try right now with a site like Try Handlebars.js to interactively craft a template that takes some of your sample JSON and output the HTML you desire.
In all likelihood, a {{#each}} with another {{#each}} inside of it could probably handle the conversion of a nested JSON to whatever HTML you're after.