I have this code to make the data available in table format but the table head and row appear as two different body, how do i work with that
$("#container").html("<table> <th>Name</th> <th>Address</th> <th>Sex</th> <th>Email</th>")
for (var i = 0; i < data.length; i++) {
$("#container").append("<tr><td>" +
data[i].name + "</td><td>" +
data[i].address + "</td><td>" +
data[i].sex + "</td><td>" +
data[i].email + "</td><tr>"
);
}
$("container").append("</table>")
This is what I get
I want the whole table, not two seperate buddies.
var htmlTable = '<table><tr><th>Name</th><th>Adress</th><th>Sex</th> <th>Email</th></tr>';
for(var i = 0; i < data.length; i++) {
htmlTable += '<tr><td>' + data[i].name + '</td><td>' + data[i].adress + '</td><td>' + data[i].sex + '</td><td>' + data[i].email + '</td></tr>';
}
htmlTable += '</table>';
$('#container').html(htmlTable);
Add the table to the DOM at once, otherwise the browser will have problems rendering it.
You can't append <table> and </table> separately, appending DOM elements (by setting innerHTML behind the scene) is not the same as string concatenation. Browser detects invalid markup and fixes it accordingly by adding missing parts of the table. So as the result you get one table after first append, and in the loop you are appending rows into #container, not the table, which is rendered incorrectly.
To fix try something like this:
var $table = $("#container").html("<table><tr><th>Name</th><th>Address</th><th>Sex</th><th>Email</th></tr></table>");
for (var i = 0; i < data.length; i++) {
$table.append("<tr><td>" + data[i].name + "</td><td>" + data[i].address + "</td><td>" + data[i].sex + "</td><td>" + data[i].email + "</td></tr>");
}
Note, I also cached $table variable so you don't query DOM in each iteration.
Also pay attention to closing tags, in your code you have couple of problems like <tr> where it should be </tr>.
You need to add <tr> too for <th>:
$("#container").html("<table> <tr><th>Name</th> <th>Address</th> <th>Sex</th> <th>Email</th></tr></table>")
Related
I just want to add style in my first tr on my inner HTML table how could I do this?
for (i = 0; i <= years_in_months; i++) {
var powint1 = compound * (Math.pow(interest, i));
powint1 = powint1.toFixed(0);
var ointerest = (interest - 1)*100;
ointerest = ointerest.toFixed(0);
tableHTML = tableHTML + "<tr><td>" + months2[i] + "</td><td> " + ointerest + "%"+"</td><td>"+ "$"+powint1 +"</td></tr>";
document.getElementById("tdisplay").innerHTML = "<thead><tr><th>Month</th><th>Interest</th><th>Total Amount</th></tr></thead>"+ tableHTML;
}
Use this in your css:
#tdisplay tr:nth-of-type(1) {
/* Your Style*/
}
See CSS :nth-of-type() Selector
You may want to move document.getElementById("tdisplay").innerHTML = ... outside the loop
I got the answer with my own, I just added class and put the value of i on it then do the CSS.
tableHTML = tableHTML + "<tr class='table-"+[i]+"'><td>" + months2[i] + "</td><td> " + ointerest + "%"+"</td><td>"+ "$"+powint2 +"</td></tr>";
CSS
.table-0{background-color:yellow;}
I have below line in my js code. i runs from 0 to 2. I want to put a custom text in place of: ' + info[i] + ' for each of the i's(over iterations of i). How do I do that?
for(var i=0; i < origins.length-1; i++) {
var results = response.rows[i].elements;
output += '<tr><td>' + info[i] + '</td><td>' + origins[i] + '</td><td></td><td>' + destinations[i+1] + '</td><td></td><td>' + results[i+1].distance.text + '</td></tr>';
}
. I want to put a custom text in place of: ' + info[i] + ' for each of the i's(over iterations of i).
Not sure what is "custom text" but assume your custom text should be in an array:
var customText = ["Custom text for i=0",
"Custom text for i=1",
"Custom text for i=2"];
for(var i=0; i < origins.length-1; i++) {
var results = response.rows[i].elements;
output += '<tr><td>' + customText[i] + '</td><td>' + //....
}
Also how to align the out-put of the code at the center of my webpage?
This is connected to CSS rather than with JS. Use CSS property text-align: center for a table, div or wharever you want to center.
If the custom text isn't in a variable, just put it directly into the HTML that you're generating:
output += '<tr><td>Custom Text</td><td>' + origins[i] + '</td><td></td><td>' + destinations[i+1] + '</td><td></td><td>' + results[i+1].distance.text + '</td></tr>';
Hello i'm trying to use Tablesorter(https://github.com/christianbach/tablesorter) to sort a table of mine which i generate throu JQuery.appends. This is how my code looks:
$(document).ready(function() {
*Lotsa more code .....*
$.get("../skillqueue",{keyid: keyid, charid: charid},function(xmlskillqueue){
console.log("XML Skillqueue");
console.log(xmlskillqueue);
//Variables for
var rowsets = xmlskillqueue.getElementsByTagName("rowset");
var skillrows;
for(var i = 0; i < rowsets.length; i++){
if(rowsets[i].getAttribute("name") == "skillqueue"){
skillrows = rowsets[i].getElementsByTagName("row");
}
}
//Defines Table Headers
$("#tableskillqueuelist").append(
"<thead>" +
"<tr>" +
"<th>Order: </th> "+
"<th>Skill Name: </th> "+
"<th>Training to: </th> "+
"<th>Starts:</th> "+
"<th>Ends:</th> "+
"</tr> "+
"</thead>"+
"<tbody>"
);
for(var i = 0; i < skillrows.length; i++){
(function(i, skillrows) {
$.get("../getitemname", {itemid:skillrows.getAttribute("typeID")},function(itemname){
$("#tableskillqueuelist").append(
"<tr> " +
"<td>" + skillrows.getAttribute("queuePosition") + ". " +
"<td>" + itemname + "</td>" +
"<td>" + "|Train to: " + skillrows.getAttribute("level") + "</td>" +
"<td>" + "|Training Starts: " + skillrows.getAttribute("startTime") + "</td>" +
"<td>" + "|Training Ends: " + skillrows.getAttribute("endTime") + "<td>" +
"</tr>"
);
})
})(i, skillrows[i]);
}
//Ends the table body
$("#tableskillqueuelist").append("</tbody>");
});
});
Now i'm wondering what i need to do to have it successfully run the $("#tableskillqueuelist").tablesorter(); method. Since it seems like whenever i try and run it, the #tableskillqueuelist seems to be empty.
You need to tell table sorter that you've changed the data and that you want to sort it by triggering events.
Example from the docs: http://tablesorter.com/docs/example-ajax.html
$("table").tablesorter();
$("#ajax-append").click(function() {
$.get("assets/ajax-content.html", function(html) {
// append the "ajax'd" data to the table body
$("table tbody").append(html);
// let the plugin know that we made a update
$("table").trigger("update");
// set sorting column and direction, this will sort on the first and third column
var sorting = [[2,1],[0,0]];
// sort on the first column
$("table").trigger("sorton",[sorting]);
});
return false;
});
HTH
I need to use join() as JS own method to add a table format to the values in those arrays.
This is an example of my two arrays to diplay, and the table layout should look like this.
This is the part of my code; ovbiously is not working ok, because Im getting a wrong "L" table style format when it runs.
I know its look terrible to parse HTML like that, but this code is in
Google Apps Scripts, so this table is gonna be send it by email.
Any idea how to get the proper format?
Thanks.
|-------|-------|
| user | skill |
|-------|-------|
| user | skill |
|-------|-------|
body +=
"<table style=" + STYLE.TABLE + ">" +
outUsers.join("<tr><td style=" + STYLE.TD + ">") + "</td></tr>" +
outSkills.join("<tr><td style=" + STYLE.TD + ">") + "</td></tr>" +
"</table>";
In this case Array.prototype.join() doesn't do the job I'd use Array.prototype.reduce() instead
Here is an example of what it could look like:
EDIT according to PHPglue comment to have both users and skills on the same row:
var body ='';
var outUsers = ['me', 'you', 'her'],
outSkills = ['eating', 'sleeping', 'working hard'],
STYLE = {
TABLE: "border: red;",
TD: "border: blue;"
},
getTR = function (prev, curr, index) {
return prev + '<tr>' + openingTD + curr + '</td>' + openingTD + outSkills[index] + '</td></tr>';
};
var openingTD = '<td style="' + STYLE.TD + '">';
body += '<table style="' + STYLE.TABLE + '">' +
outUsers.reduce(getTR, '') +
"</table>";
I think this is what you need to see:
var table = '<table><tbody>';
for(var i=0,l=outUsers.length; i<l; i++){
table += '<tr><td>'+outUsers[i]+'</td><td>'+outSkills[i]+'</td></tr>';
}
table += '</tbody></table>';
You should style with CSS. You should read my comments above, as well.
I am facing an issue with my jquery. I have used jQuery to add controls to table, along with a remove button to remove that particular row in table. here is my code on how i am creating controls in table.
HTML
<table id="controls" cellpadding="10" cellspacing="10">
</table>
<input id="btnAdd" type="button" value="Add" />
my jquery code looks like this
jquery
$(document).ready(function() {
$("#btnAdd").click(function() {
var field = $("#field").val();
var year = new Date().getFullYear()
var DDL_fromProfession = "<select name='ParametersFromProf' id='DDL_FromProYear'>";
for (var i = 1950; i <= year; i++) {
DDL_fromProfession += "<option text='" + i + "' value='" + i + "'>" + i + "</option>";
}
DDL_fromProfession += "</select>";
var DDL_ToProfession = "<select name='ParametersToProf' id='DDL_ToProYear'>";
for (var i = 1950; i <= year; i++) {
DDL_ToProfession += "<option text='" + i + "' value='" + i + "'>" + i + "</option>";
}
DDL_ToProfession += "</select>";
var newRow1 = "<tr><td align='center' style='font-size: large; color: #212121;' height='35px'>from"
+ DDL_fromProfession + " to " + DDL_ToProfession + "</td></tr>"
+ "<tr><td align='center' style='font-size:large;color:#212121;' height'35px'>"
+ "<input type='checkbox' name='chkbx_CurrPro' value='" + k + "'>I currently work here</input>";
newRow1 += "<br/><button id='btn_rmv'>Remove</button>";
var input = "<input name='parameters' id='field' type='text' />";
var input1 = "<input name='parametersCompany' id='field' type='text'/>"
//var inputCurrent="<input name='Current' id='Currfield' type='hidden'/>"
var newRow = "<tr><td align='center' style='font-size: x-large; color: #212121;' height='35px'>"
+ input + " at " + input1 + "</td></tr>";
$('#controls').append(newRow);
$('#controls').append(newRow1);
});
});
to remove last row i am using.
jquery
$(document).ready(function() {
$("#controls").delegate("#btn_rmv", "click", function() {
$(this).closest("tr").remove();
return false;
});
});
clicking on remove button refresh the page and remove all the rows that i have added instead of last one.
NOTE: What i ahve digged out is .delegate is server side and it refresh the page. i am unable to remove last row with $("#btn_rmv").click(function() on my page
Please point me to right direction.
Thanks in advance
The code in question does not work as k is not defined, as used in the line
value='" + k + "'
If this error is corrected then the next problem is that you are creating multiple elements with the same id, as seen here
newRow1 += "<br/><button id='btn_rmv'>Remove</button>";
which in invalid HTML and will cause problems for jQuery in finding the element with the unique id.
By changing k for 0 and changing the id to a class, the remove code will only remove the current row with the button on. I assume that you really want to remove that row and also the preceding 2 rows.
$('#controls').delegate('.btn_rmv', 'click', function() {
var index = $(this).closest('tr').index() + 1 // as nth-child is 1-based indexing
$('#controls tr:nth-child(n+' + (index - 2) + '):nth-child(-n+' + index + ')').remove(); // remove 3 rows
return false
});
See demo
Please note that since jQuery 1.7, .delegate() is superseded by .on() so the updated function is:
$('#controls').on('click', '.btn_rmv', function() {
var index = $(this).closest('tr').index() + 1
$('#controls tr:nth-child(n+' + (index - 2) + '):nth-child(-n+' + index + ')').remove();
return false
});
I had a similar experience: I was using Google Chrome and it would refresh the page everytime I called a function. You will have to return false. My problem was when I called a function from an element using "onclick". When I called the function from onclick I had to include the "return false;":
onclick="return false; functionName()"
Try this and see if it works:
$(document).ready(function() {
$("#btnAdd").click(function() {
/* YOUR CODE */
return false;
});
});
Or this and see if it works:
$(document).ready(function() {
$("#btnAdd").click(function() {
/* YOUR CODE */
});
return false;
});
Sorry my Javascript is not very good :(
You can do it in this way..
var RowCount = 0;
$(document).ready(function() {
$("#btnAdd").click(function() {
RowCount = RowCount + 1;
var newRow1 = "<tr id='tr" + RowCount + "'><td align='center' style='font-size: large; color: #212121;' height='35px'>from"
+ DDL_fromProfession + " to " + DDL_ToProfession + "</td></tr>"
+ "<tr><td align='center' style='font-size:large;color:#212121;' height'35px'>"
+ "<input type='checkbox' name='chkbx_CurrPro' value='" + k + "'>I currently work here</input>";
newRow1 += "<br/><button id='btn_rmv' onclick='RemoveRow(" + RowCount + ")'>Remove</button>";
});
});
function RemoveRow(RowID) {
$('#RemoveRow' + RowID).remove();
}
It looks like you are hooking up the remove click handler on $(document).ready.
On document.ready, the remove buttons do not yet exist (since they are generated dynamically when clicking 'Add', after the document.ready code has run). That's why $("#btn_rmv").click(function()... is not working.
So, after dynamically inserting a remove button in the $("#btnAdd").click event, you explicitly have to add a click handler to it.
EDIT:
If you generate your remove buttons with a unique id (eg. btn_rmv_1, btn_rmv_2, etc), you can add the following to your Add-handler (after appending the new button to the DOM):
$('#btn_rmv_1').click(removeButtonFunction);