Generate a simple table with javascript - javascript

I dont understand why but I'm getting the wrong body structure. You can see on the image that I get a <tr></tr> and I dont have that on javascript.
I just want a table with 3 columns and up to 10 rows.
What's happening?
My generated html
JavaScript
$('#selectMRPC').change(function () {
//fetch data
var mrpc = $(this).find('option:selected').data('mrpc');
$('#paramBody').empty();
for (var i = 1; i <= 10; i++) {
var field = mrpc["field" + i];
if (field !== undefined) {
var parsedField = field.split('_');
var value = parsedField[0];
var type = parsedField[1];
switch (type) {
case "S":
type = "text";
if (value === '""')
value = null;
break;
case "B":
type = "checkbox";
break;
case "N":
type = "number";
value = parseInt(value);
break;
case "D":
type = "number";
value = parseInt(value);
if (value === '""')
value = null;
break;
}
$('#paramBody').append('<tr>');
$('#paramBody').append('<td>' + i + '</td>');
$('#paramBody').append('<td>' + type + '</td>');
$('#paramBody').append('<td><input name="Fields" type="' + type + '">').val(value);
$('#paramBody').append('</tr>');
}
}
});

store everything in a var then add it to dom :
var html = "";
html += '<tr>';
html += '<td>' + i + '</td>';
html += '<td>' + type + '</td>';
html += '<td><input name="Fields" type="' + type + '" value="' + value +'">';
html += '</tr>';
$('#paramBody').append(html);

You are appending everything to #paramBody, which is incorrect. Consecutively, you need to append/insert data into <tr>. So I would recommend, you concatenate everything together instead of appending.
You need to change
$('#paramBody').append('<tr>');
$('#paramBody').append('<td>' + i + '</td>');
$('#paramBody').append('<td>' + type + '</td>');
$('#paramBody').append('<td><input name="Fields" type="' + type + '">').val(value);
$('#paramBody').append('</tr>');
to
var rowHtml = '<tr>' + '<td>' + i + '</td>' + '<td>' + type + '</td>' + '<td><input name="Fields" type="' + type + '">' + value + '</tr>';
$('#paramBody').append(rowHtml);

append will create an element from the parameter if the given input is not already a valid html string
Make it
$('#paramBody').append('<tr><td>' + i + '</td><td>' + type + '</td><td><input name="Fields" type="' + type + '" value="' +value + '"></tr>');
Or append them one by one (example below)
$( "<tr></tr>" ).append('<td>' + i + '</td>').appendTo( '#paramBody' );
Or create a string first
var html = '<tr>';
html += '<td>' + i + '</td>';
html += '<td>' + type + '</td>';
html += '<td><input name="Fields" type="' + type + '" value="' + value + '">';
html += '</tr>';
$('#paramBody').append(html );

Related

How to by pass HTML encoding string in text fields?

I am setting a field in my HTML label from Viewbag which has a "'" in the text. when the HTML pulls up it shows ' in place of "'". How do I stop it from getting encoded?
Please find the code below.
setting text fileds in the HTML view.
$('#thStudentName').text('#ViewBag.Name');
if (sessionData.data.EventDate2Def != '' || sessionData.data.EventDate2Def != null)
$('#tdWhen').text(sessionData.data.EventDate1Def + ' and ' + sessionData.data.EventDate2Def);
else
$('#tdWhen').text(sessionData.data.EventDate1Def);
$('#tdWhere').text(sessionData.data.FacilityName);
$('#tdLocated').text(sessionData.data.Address1 + ', ' + sessionData.data.City + ', ' + sessionData.data.State + ' ' + sessionData.data.Zip);
$('#tdPhone').text(sessionData.data.Phone);
$('#tdDirections').text(sessionData.data.Directions);
$('#tdRoom').text(sessionData.data.RoomNumber);
Populating a different section with Dynamic data.
function populateSessionTable() {
var count = 1;
$('#SessionTable').html('');
var tableContent = '';
var record = '';
var Sessions = sessionData.data.Sessions;
tableContent = generateTableContent(count, Sessions[0].StartDateTimeDef);
tableContent += '</tbody></table></div>';
$('#SessionTable').html(tableContent);
var radioStatus = '';
for (var i = 0; i < Sessions.length; i++) {
var content = Sessions[i];
radioStatus = '';
if (content.Capacity == content.Registered || content.Closed)
radioStatus = '<input disabled class="selected-session radio" name="SessionId" type="radio" value="' + content.SessionId + '">';
else if (content.StartDateTimeDef == '#ViewBag.WorkshopDateDef' && t24to12Convert(content.StartTimeString) == t24to12Convert('#ViewBag.WorkshopTime'))
radioStatus = '<input class="selected-session radio" checked name="SessionId" type="radio" value="' + content.SessionId + '">';
else
radioStatus = '<input class="selected-session radio" name="SessionId" type="radio" value="' + content.SessionId + '">';
record += '<tr>';
record += '<td class="session-schedule-table-btn">';
record += radioStatus;
record += '</td>';
record += '<td class="session-schedule-table-session-number"> ' + content.Number + ' </td>';
record += '<td class="session-schedule-table-session-start-time">' + t24to12Convert(content.StartTimeString) + '</td>';
record += '</tr>';
$('#SessionTBody' + count).append(record);
record = '';
if(Sessions.length != i + 1)
{
if(Sessions[i].StartDateTimeDef != Sessions[i + 1].StartDateTimeDef)
{
tableContent = '';
count++;
tableContent = generateTableContent(count, Sessions[i+1].StartDateTimeDef);
tableContent += '</tbody></table></div>';
$('#SessionTable').append(tableContent);
}
}
}
}
populateSessionTable();
The preview shows the name in the correct format, but when it gets rendered instead of having the quote, it shows '
This is how the output is coming up
So finally it was a stupid problem and I swear I had tried this before, but this is the code that worked.
var stuName = '#ViewBag.Name';
stuName = stuName.replace("'", "'");
$('#thStudentName').text(stuName);

Dynamic Row addition to the Table

I want to add Array elements to the table.
Array elements are dynamic coming from the database. And i am creating the Row for adding the one row from the generated data and appending rowAfter to add the other array elements
Here is the code i have written -
var rowSpan = 0;
var rowSpan1 = 0;
for (element in data)
{
// get products into an array
var productsArray = data[element].products.split(',');
var QuantityArray = data[element].quantity.split(',');
var ChemistArray = data[element].Retailername.split(',');
var PobArray = data[element].Pob.split(',');
rowSpan = productsArray.length;
rowSpan1 = ChemistArray.length;
var row = '<tr>' +
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].doctor_name + '</td>';
// loop through products array
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
row += '<td>' + QuantityArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td><td>' + QuantityArray[i] + '</td>';
}
}
for (var k = 0; k < rowSpan1; k++) {
if(k == 0) {
row += '<td>' + ChemistArray[k] + '</td>';
row += '<td>' + PobArray[k] + '</td>';
} else {
rowAfter += '<td>' + ChemistArray[k] + '</td><td>' + PobArray[k] + '</td> </tr>';
}
}
row +=
'<td rowspan="'+rowSpan1+'">' + data[element].locations +'</td>'+
'<td rowspan="'+rowSpan1+'">' + data[element].area + '</td>'+
'</tr>';
$('#tbody').append(row+rowAfter);
So as per the code I can finely display ProductArray and Quantity Array
And But i am not able to display the Chemist array after one another.
In the above Image i want to display data( Kapila and Kripa below the Chemist column) Some where making issue with tr and td.
Any help would really appreciated.
Data is a JSON Response -
In my case, ChemistArray(Retailername in response) contains 4 names and POBArray 4 values.
You need to add an empty <td></td> as a "placeholder".
for (element in data) {
var productsArray = data[element].products.split(',');
var quantityArray = data[element].quantity.split(',');
var chemistArray = data[element].Retailername.split(',');
var pobArray = data[element].Pob.split(',');
// find the largest row number
var maxRows = Math.max(productsArray.length, quantityArray.length, chemistArray.length, pobArray.length);
var content = '';
var date = '<td rowspan="' + maxRows + '">' + data[element].date + '</td>';
var doctorName = '<td rowspan="' + maxRows + '">' + data[element].doctor_name + '</td>';
var locations = '<td rowspan="' + maxRows + '">' + data[element].locations + '</td>';
var area = '<td rowspan="' + maxRows + '">' + data[element].area + '</td>';
content += '<tr>' + date + doctorName;
for (var row = 0; row < maxRows; row++) {
// only add '<tr>' if row !== 0
// It's because for the first row, we already have an open <tr> tag
// from the line "content += '<tr>' + date + doctorName;"
if (row !== 0) {
content += '<tr>';
}
// the ternary operator is used to check whether there is items in the array
// if yes, insert the value between the <td></td> tag
// if not, just add an empty <td></td> to the content as a placeholder
content += '<td>' + (productsArray[row] ? productsArray[row] : '') + '</td>';
content += '<td>' + (quantityArray[row] ? quantityArray[row] : '') + '</td>';
content += '<td>' + (chemistArray[row] ? chemistArray[row] : '') + '</td>';
content += '<td>' + (pobArray[row] ? pobArray[row] : '') + '</td>';
// only add "locations + area + '</tr>'" if it is the first row
// because locations and area will span the whole column
if (row === 0) {
content += locations + area + '</tr>';
} else {
content += '</tr>';
}
}
$('#tbody').append(content);
}
content += '<td>' + (productsArray[row] ? productsArray[row] : '') + '</td>'; is just a short-hand for
content += '<td>';
if (productsArray[row]) {
content += productsArray[row];
} else {
content += '';
}
content += '</td>';
If there is item in the productsArray[row], let's say productsArray[0], which is 'Sinarest', then productsArray[row] would be truthy. Else, if there is no more products in the array, such as productsArray[3] will gives us undefined, which is a falsy value and the corresponding conditional will be ran.

how to append value in td

I am getting dynamic values in table using Datatables. I am getting my desired value in alert, but I want to show that value in table. for that purpose I used .append, .html but no luck. How can I show = my value in <td>. I also try to gave gave td an id e.g <td id="files">
here is my code:
function format(d) {
var str = d.files;
var myarr = str.split(",");
for (var i = 0; i < myarr.length; i++) {
alert(myarr[i]);
$("#files").append("<a href='/uploads/" + myarr[i] + "'>" + myarr[i] + "</a>");
}
// `d` is the original data object for the row
return '<table id="ChildRows" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Contact Person:</td>' +
'<td>' + d.person + '</td>' +
'</tr>' +
'<tr>' +
'<td>Phone:</td>' +
'<td>' + d.phone + '</td>' +
'</tr>' +
'<tr>' +
'<td>Web:</td>' +
'<td>' + d.web + '</td>' +
'</tr>' +
'<tr>' +
'<td>Trade Type:</td>' +
'<td>' + d.ttype + '</td>' +
'</tr>' +
'<tr>' +
'<td>Files:</td>' + '<td id="files">'
'</td>' +
'</tr>' +
'</table>';
}
I hope it will be a easy fix.any help will be highly appreciable
Your issue is that the #files element doesn't exist at the point you attempt to select it. You need to first add that HTML string to the DOM, then append to it.
Alternatively, you could amend the logic which creates that HTML string to include the output of your for loop, like this:
function format(d) {
var str = d.files;
var filesHtml = str.split(",").map(function(file) {
return '' + file + '';
});
return '<table id="ChildRows" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Contact Person:</td>' +
'<td>' + d.person + '</td>' +
'</tr><tr>' +
'<td>Phone:</td>' +
'<td>' + d.phone + '</td>' +
'</tr><tr>' +
'<td>Web:</td>' +
'<td>' + d.web + '</td>' +
'</tr><tr>' +
'<td>Trade Type:</td>' +
'<td>' + d.ttype + '</td>' +
'</tr><tr>' +
'<td>Files:</td>' +
'<td id="files">' + filesHtml + '</td>' +
'</tr>' +
'</table>';
}
var html = format({
person: 'John Smith',
phone: '1234 567890',
web: 'http://google.com',
ttype: 'Foobar',
files: 'a.jpg,b.jpg'
});
$('div').append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

how do i append in this function?

i have this code:
for (var i = 0; i < data.times.length; ++i) {
var time = formatTime(data.times[i].time);
tableContent += '<tr><td>' + data.times[i].destination.name + '</td><td id="appendLate' + i + '">' + time + '</td><td>' + data.times[i].track + '</td><td>' + data.times[i].train_type + '</td><td>' + data.times[i].company + '</td></tr>'
// laat vertragingen zien (BETA)
if (data.times[i].delay / 60 >= 1) {
$('#appendLate' + i + '').append("+" + data.times[i].delay / 60).addClass("late");
}
}
table.html(tableContent);
}
The if statement appends stuff and adds a class. i know it wont work like this.. but i cant seem to get how it WIL work.. Can some one help?
See it live: http://codepen.io/shiva112/pen/JGXoVJ?editors=001
Well, you're basically almost there. The right way to do it is to build the entire string before doing any DOM manipulation, since DOM operations are very slow (relatively).
Let's say your index.html looks like:
<html>
<head>
<title>Cool site!</title>
</head>
<body>
<table id="myCoolTable"></table>
</body>
</html>
Then your JavaScript simply becomes:
var tableContent = '';
for (var i = 0; i < data.times.length; ++i) {
var time = formatTime(data.times[i].time);
tableContent += '<tr>'
+ '<td>' + data.times[i].destination.name + '</td>';
if (data.times[i].delay / 60 >= 1) {
tableContent += '<td id=\'appendLate\'' + i + ' class=\'late\'>' + time + '</td>' + '+' + (data.times[i].delay / 60);
} else {
tableContent += '<td id=\'appendLate\'' + i + '>' + time + '</td>';
}
tableContent += '<td id=\'appendLate\'' + i + '>' + time + '</td>'
+ '<td>' + data.times[i].track + '</td>'
+ '<td>' + data.times[i].train_type + '</td>'
+ '<td>' + data.times[i].company + '</td>'
+ '</tr>';
}
$('#myCoolTable').html(tableContent);
What this does is build the HTML for the entire table. Then update the table only once. Hope it helps!

Javascript / jQuery changing cell of a table based on the value

Hi i have a javascript function that take the contents of a JSON file and the puts it in to a table, here is the code.
$.getJSON("People.json",
function(data) {
$.each(data.People, function(i, PersonObj) {
var Person = PersonObj[Object.keys(PersonObj)[0]];
content = '<tr>';
content += '<tbody>';
content += '<td>' + Person.Op + ' </td>';
content += '<td>' + Person.Name + ' </td>';
content += '<td>' + Person.WorkHours + ' </td>';
content += '<td>' + Person.Start + ' </td>';
content += '<td>' + Person.End + ' </td>';
content += '<td>' + Person.Clock + ' </td>';
content += '<td>' + Person.OFF + ' </td>';
content += '<td>' + Person.ON + ' </td>';
content += '<td>' + Person.OUT + ' </td>';
content += '</tr>';
content += '</tbody>';
content += '<p>';
$(content).appendTo("tbody");
console.log(Person);
});
});
However what i need is to some formatting via if statements so for example
normally i would use something like the badly put together bunch of If statements.
if (Person.clock !== false) {
document.getElementById('the cell where Person.Op is placed').style.backgroundColor = 'lime';
}
if (Person.Off !== false) {
document.getElementById('the cell where Person.Op is placed').style.backgroundColor = 'red';
}
if (Person.on !== false) {
document.getElementById('the cell where Person.Op is placed').style.backgroundColor = 'lime';
}
if (Person.out !== false) {
document.getElementById('the cell where Person.Op is placed').style.backgroundColor = 'red';
}
However i am struggling to find the best way of putting what i already have with the function for creating the table and putting the formatting from the If statements together
what would be the best way to do this?
Why not add a class to each such case. something like this:
$.getJSON("People.json",
function(data) {
$.each(data.People, function(i, PersonObj) {
var Person = PersonObj[Object.keys(PersonObj)[0]];
content = '<tr>';
content += '<td>' + Person.Op + ' </td>';
content += '<td>' + Person.Name + ' </td>';
content += '<td>' + Person.WorkHours + ' </td>';
content += '<td>' + Person.Start + ' </td>';
content += '<td>' + Person.End + ' </td>';
content += '<td class="'+(Person.clock? 'hasClock' : '') +'">' + Person.Clock + ' </td>';
content += '<td>' + Person.OFF + ' </td>';
content += '<td>' + Person.ON + ' </td>';
content += '<td>' + Person.OUT + ' </td>';
content += '</tr>';
$(content).appendTo("tbody");
console.log(Person);
});
});
and then add a class to your css:
.hasClock{
background-color :lime;
}
$.getJSON("People.json",
function(data) {
$.each(data.People, function(i, PersonObj) {
var Person = PersonObj[Object.keys(PersonObj)[0]];
content = '<tr>';
content += '<tbody>';
content += '<td class="op ' + Person.Op + '">' + Person.Op + ' </td>';
content += '<td>' + Person.Name + ' </td>';
content += '<td>' + Person.WorkHours + ' </td>';
content += '<td>' + Person.Start + ' </td>';
content += '<td>' + Person.End + ' </td>';
content += '<td>' + Person.Clock + ' </td>';
content += '<td>' + Person.OFF + ' </td>';
content += '<td>' + Person.ON + ' </td>';
content += '<td>' + Person.OUT + ' </td>';
content += '</tr>';
content += '</tbody>';
content += '<p>';
$(content).appendTo("tbody");
console.log(Person);
});
});
Add class to your td's with the value. If you have definite values coming up, then you can create css selectors for that with the CSS properties you want.
Suppose you had value of op as someOpValue
You could write your css like foloowing.
td.op.someOpValue{
background : red;
}

Categories

Resources