Format table generated with .js file in Javascript - javascript

I have a table that is generated with data from a .js file. What I want to do is be able to format rows ex. give them different color. I know you can add a class like <tr class="yellowrow"></tr> but the way the code is I can't do it like that. I'm thinking a for loop might do.. any ideas?
<table id="data">
<thead>
<tr>
<th>Date</th>
<th>Amount</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<script type="text/javascript" src="js/people.js"></script>//file with information
<script type="text/javascript" >
for(var i=0; i<Name.length;i++){
document.write('<tr><td>' + date[i] + '</td><td>' + amount[i] + '</td><td>'
+Name[i]'</td></tr>');//this brings in the data to generate the rows
}
</script>
</tbody>
//so this gives me a table with a couple of rows... how can i format each row they
need to have different classes because they cant all have the same format.like one
can be blue, another red, another blue..ect.

Short answer: You can use CSS to style the different rows.
tr:nth-child(2n){
background-color: #ccc;
}
tr:nth-child(3n){
background-color: #444;
}
https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
Long, mostly unrelated answer: You shouldn't be using document.write. You can add to the tbody a lot more elegantly like this.
<table id="data">
...
<tbody></tbody>
</table>
<script>
var rows = [];
for (var i=0; i<Name.length; i++){
rows.push(
'<tr>' +
'<td>' + date[i] + '</td>' +
'<td>' + amount[i] + '</td>' +
'<td>' + Name[i] + '</td>' +
'</tr>'
);
}
document.querySelector('#data tbody').innerHTML = rows.join('');
</script>
Why is document.write considered a "bad practice"?

if your just looking to alternate the colors you could just use a css selector like:
tr:nth-child(odd)
http://www.w3.org/Style/Examples/007/evenodd.en.html

Related

How can I delete all the columns in the Dynamic DataTable?

First, I want to delete all the columns and then use the select command to bring all the columns back for perform the refresh operation on the DataTable without refreshing page. So I need a piece of code that I can delete all the columns.
I shared my html and javascript code as shown following.
Can someone help me about this regard?
//CSHTML
<table id="datatables" class="table table-striped table-no-bordered table-bigboy" cellspacing="0" style="width:100%;">
<thead>
<tr>
<th class="disabled-sorting">Room Plan</th>
<th>Name</th>
<th class="disabled-sorting text-right">Actions</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Room Plan</th>
<th>Name</th>
<th class="text-right">Actions</th>
</tr>
</tfoot>
<tbody id="colmn">
#* *#
</tbody>
</table>
//*********************************JS*********************************//
//-------------------------SELECT ROOM START----------------------------
$.post("/Home/selectRooms", {}, function (data) {
var ndx = 0;
$.each(data.xroom_name, function (key, value) {
var Xroom_name = data.xroom_name[ndx];
var Xroom_plan = data.xroom_plan[ndx];
var column =
('<tr>' +
'<td>' +
'<div class="img-container">' +
'<img src="../../assets/img/room-plan/' + Xroom_plan + '" alt="..." id="imgsrc">' +
'</div>' +
'</td>' +
'<td id="imgname">' + Xroom_name + '</td>' +
'<td class="text-right">' +
'<i class="fa fa-edit"></i>' +
'</i>' +
'</td>' +
'</tr>');
document.getElementById('colmn').innerHTML = document.getElementById('colmn').innerHTML + column;
ndx++;
});
});
I also delete the column information that I clicked like this:
var table = $('#datatables').DataTable();
table.on('click', '.remove', function (e) {
$tr = $(this).closest('tr');
table.row($tr).remove().draw();
e.preventDefault();
});
I want to delete all columns because of I can refresh the table immediately after adding, updating and deleting. I do not want to delete the column that I clicked only.

Trying to bind column dynamically in a table using jquery

I am trying to bind column dynamically in a table using jQuery .but click event is not working while trying to click 'btnASizeR' and 'btnWdDelete' button event is not working .Any idea would be appreciated.
$(function() {
var i = 0;
$('#btnASizeR').click(function() {
/* To check the count of already exist tr in WireDimTbl and then assigning the i value for controlids*/
var i = $("#WireDimTbl tbody>tr").length + 1;
/* To check the count of already exist tr in WireDimTbl and then assigning the i value for controlids*/
var sizerangeMin = "<input type='text' ID='SizeMin" + i + "' name='SizeMin' value='2.00' />";
var sizerangeMax = "<input type='text' ID='SizeMax" + i + "' name='SizeMax' value='3.00' />";
var ToleranceMin = "<input type='text' ID='TolMin" + i + "' name='TolMin' value='1' />";
var ToleranceMax = "<input type='text' ID='TolMax" + i + "' name='TolMax' value='1' />";
var markup = "<tr><td>" + sizerangeMin + "</td><td>" + sizerangeMax + "</td><td>" + ToleranceMin + "</td><td>" + ToleranceMax + "</td></tr>";
$("#WireDimTbl tbody").append(markup);
});
$('#btnWdDelete').click(function() {
$("#WireDimTbl tbody>tr:last").remove();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td class='text-left'><strong>Wire Dimensions</strong></td>
</tr>
<tr>
<td class='text-left'><strong>Standard Sizes & Tolerances</strong></td>
<td>
<input type="button" id="btnASizeR" value="AddSizeRange" />
<input type="button" id="btnWdDelete" value="Delete" />
<table id="WireDimTbl" class="table table-bordered">
<thead>
<tr>
<th class="text-center">Size Range Min (mm)</th>
<th class="text-center">Size Range Max (mm)</th>
<th class="text-center">Tolerance (-)mm</th>
<th class="text-center">Tolerance (+) mm</th>
</tr>
</thead>
<tbody></tbody>
</table>
</td>
</tr>
You mentioned that you are loading the table dynamically. Do you mean that when the page first loads the table is missing and its added later?
If that is the case, are you sure the code is called that binds the click events? The above example binds the events on page_load however, if the buttons are not yet available on the page it won't be able to bind it. JQuery will not automatically bind future elements.
Try settings a console.log($('#btnASizeR')); before binding the click event to make sure that JQuery can actually find the button.

Delete a table row on button click in Javascript

I have a table with the following 3 columns where each row is dynamically appended.
Condition : Is a mere WHERE clause conditional statement string
Remove : A button that removes that row (Removes a condition)
Join with : A drop down combo
When the user clicks on the Remove button, that particular row needs to be removed.
I have written the code for this, but nothing happens and am not getting any errors on the console as well.
Code in Context
$("#whereConditionTable").append(
"<tr>"+
"<td>"+conditionString+"</td>"+
"<td><button id='removeConditionBtn' name='removeConditionBtn' class='btn btn-default'><img src='resources/images/removeWhereCondition.png' width='25px' height='25px'></button>"+
"<td>"+
"<select id='where-Condition-Join-Combo' name='where-Condition-Join-Combo' class='form-control'>"+
"<option value='1'>Join using</option>"+
"<option value='2'>AND</option>"+
"<option value='3'>OR</option>"+
"</select>"+
"</td>"+
"</tr>"
);
document.getElementById("removeConditionBtn").addEventListener("click", function() {
removeWhereCondition();
}, false);
removeWhereCondition()
function removeWhereCondition()
{
$(this).closest("tr").remove();
}
Any suggestions in this regard will be highly appreciated.
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
}
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
<tr>
<td>Row 1</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
<tr>
<td>Row 2</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
<tr>
<td>Row 3</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
</table>
</body>
</html>
Few things to fix:
You're combining jQuery and vanilla JavaScript (getElementById), so I've tidied some of that up and rewritten it as jQuery.
HTML documents can not have repeating IDs. If your append ran more than once, it would create additional #removeConditionBtn and #where-Condition-Join-Combo elements, and JS would cease to work. I've changed these to classes, which are reusable.
Your addEventListener to bind a click event was only going to bind to (one) #removeConditionBtn element that existed when the code was first run. If the table contents changed to include additional buttons, your binding wouldn't have updated (even if you were using class rather than ID). I've rewritten this using jQuery on on the table itself, so the click event will still fire even as the contents of the table change.
Working demonstration below:
var conditionString = "text";
$("#whereConditionTable").append(
"<tr>" +
"<td>" + conditionString + "</td>" +
"<td><button class='removeConditionBtn' name='removeConditionBtn' class='btn btn-default'><img src='resources/images/removeWhereCondition.png' alt='Remove' width='25px' height='25px'></button>" +
"<td>" +
"<select class='where-Condition-Join-Combo' name='where-Condition-Join-Combo' class='form-control'>" +
"<option value='1'>Join using</option>" +
"<option value='2'>AND</option>" +
"<option value='3'>OR</option>" +
"</select>" +
"</td>" +
"</tr>"
);
$("#whereConditionTable").on("click", ".removeConditionBtn", function() {
$(this).closest("tr").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="whereConditionTable"></table>
Apparently you are using jQuery. You could try:
$('#removeConditionButton').on('click', function(element) {
$(element).closest('tr').remove();
})
By the way, it seem you are using id-property incorrectly. Id's should be unique and each page can have only one element with same id. In this case, you should use class instead of id.

How to populate html table using javascript without using div?

I am trying to fill html table(my table got 3 columns) with data from json using javascript but the data never get filled using div method! could any tell me how to fill content of table rows using without using div ?
for(i in json)
{
var div = "<tr id=\""+i+"\">\n" +
"<td>"+i+"</td>\n" +
"<td><img src=\""+ json[i].thumb +"\" height=\"42\" width=\"42\"></td>\n" +
"<td>\n" +
"" + json[i].title + "<br> \n" +
"<br></td></tr>\n\n";
$("#myDiv").append(div);
}
Table to be filled:
<table id="list" cellspacing="0" border="1">
<tr>
<th>Item#</th>
<th>Logo</th>
<th>Description</th>
</tr>
<div id='myDiv'></div>
</table>
This Your new table:
<table id="list" cellspacing="0" border="1">
<thead>
<tr>
<th>Item#</th>
<th>Logo</th>
<th>Description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
And code:
var html = '';
for(var i in json)
{
html += '<tr id="'+i+'">';
html += '<td>'+i+'</td>';
html += '<td><img src="'+json[i].thumb+'" height="42" width="42"></td>';
html += "<td>";
html += "" + json[i].title + "<br/><br/>";
html += '</td>';
html += '</tr>';
}
$('#list > tbody').html(html);

using datatables for non-table layouts

So I'd like to use datatables such that each "row" looks like this (or at least has this general structure):
For reference here's the HTML I used to create that:
<table border="1" cellspacing="1" cellpadding="1">
<tr>
<td colspan="2">joe bob</td>
</tr><tr>
<td rowspan="4">pic</td>
</tr><tr>
<td>DOB: 1/1/1970</td>
</tr><tr>
<td>Gender: M</td>
</tr><tr>
<td>Phone: 111-111-1111</td>
</tr>
</table>
Anyway, how might I achieve this with datatables? It seems to me that datatables returns a single <tr> but the HTML I used to produce the above has a whole bunch of <tr>'s.
I'd like to use datatables for it's ajaxified pagination and searching and for a consistent look and feel with other tables on this site.
You could do something like this in your datatable init code(untested):
'aoColumns': [
'mRender': function (data, type, full) {
return '<table border=\'1\' cellspacing=\'1\' cellpadding=\'1\'>' +
'<tr>' +
'<td colspan=\'2\'>' + full[0] +'</td>' +
'</tr><tr>' +
'<td rowspan=\'4\'>' + full[1] +'</td>' +
'</tr><tr>' +
'<td>DOB: ' + full[2] +'</td>' +
'</tr><tr>' +
'<td>Gender: ' + full[3] +'</td>' +
'</tr><tr>' +
'<td>Phone: ' + full[4] +'</td>' +
</tr>';
</table>
}
This way you're explicitly defining the row output. This would produce an 'inner' table within each datatable row, which may not be what you want. You might be able to create the inner layout using css instead of tables, but the idea would be the same. You could use a templating system like jsRender to make it a bit cleaner too.

Categories

Resources