Add items of array in javascript - javascript

I want to add price of all items in form of total from below code.
document.getElementById('form-signin').addEventListener('submit', saveItem);
function saveItem(e){
var items= document.getElementById('items').value;
var date= document.getElementById('date').value;
var price= document.getElementById('price').value;
var expense= {
items: items,
date: date,
price: price
}
if(localStorage.getItem('bill')==null){
var bill=[];
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(bill));
} else{
var bill = JSON.parse(localStorage.getItem('bill'));
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(bill));
console.log(bill);
}
e.preventDefault();
}
function fetchResult(){
var bill = JSON.parse(localStorage.getItem('bill'));
var result = document.getElementById('total');
result.innerHTML='';
for(var i=0;i < bill.length;i++){
var items= bill[i].items;
var date= bill[i].date;
var price= bill[i].price;
result.innerHTML+= '<table class="table table-bordered">' + '<tr>'+
'<th>'+'Items'+'</th>'+
'<th>'+'Date'+'</th>'+
'<th>'+'Price'+'</th>'+
'</tr>'+ '<tr>'+
'<td>'+ items + '</td>'+
'<td>'+ date+ '</td>'+
'<td>'+ price + '</td>'+
'</tr>'+ '</table>';
}
This is output of aboce. Now how to calculate total ??

Eduardo's sample will work, but I went a little further if you're interested in another way to accomplish what you're doing. I made some changes to help you prevent duplicating column headers and clean up the table generation a bit. This code does require jQuery however, and the table needs to already exist.
The form is just there because I needed something to test against... you can remove that part.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form>
Items: <input type="text" id="items"><br>
Date: <input type="text" id="date"><br>
Price: <input type="text" id="price"><br>
<input type="submit" value="Submit" onClick="saveItem()" >
</form>
<table id="tbl-items" class="table table-bordered"><thead><tr><th>Items</th><th>Date</th><th>Price</th></tr></thead><tbody id="tbl-items-body"></tbody></table>
<script>
document.getElementById('form-signin').addEventListener('submit', saveItem);
function saveItem(){
var bill=[];
var expense= { // didn't need the variables.
items: document.getElementById('items').value,
date: document.getElementById('date').value,
price: document.getElementById('price').value
}
if(localStorage.getItem('bill') != null){
bill = JSON.parse(localStorage.getItem('bill'));
}
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(bill))
console.log(bill);
}
function fetchResult(){
var bill = JSON.parse(localStorage.getItem('bill'));
var totalItems = 0;
var totalPrice = 0;
for(var i=0;i < bill.length;i++){
totalItems++;
totalPrice += bill[i].price;
$("#tbl-items-body").append(
$('<tr>').append(
'<td>' + bill[i].items + '</td><td>' + bill[i].date + '</td><td>' + bill[i].price + '</td>'
)
);
}
$("#tbl-items-body").append(
$('<tr>').append(
'<td>Total Items: ' + totalItems + '</td><td>Total Price: ' + totalPrice + '</td>'
)
);
}
</script>

In your fetchResult function while you are adding the price values and displaying in table, add to price to a total variable, then display.
function fetchResult(){
...
result.innerHTML='';
var total = 0;
for(var i=0;i < bill.length;i++){
var items= bill[i].items;
var date= bill[i].date;
var price= bill[i].price;
total += price;
result.innerHTML+= '<table class="table table-bordered">' + '<tr>'+
'<th>'+'Items'+'</th>'+
....
<span> total </span>
}

Related

populate json data in tables

javascript code
$(function(){
$(".user").on("click",function(e){
e.preventDefault();
var email = $(this).data("email");
$.ajax({
data:{email:email},
type: "POST",
url: 'getUser_detail.php',
success: function(data) {
var data = JSON.parse(data);
for (var i = 0; i < data['basic'].length; i++) {
$('#inputs').append('<label>Email:</label><input type="text" readonly class="form-control-plaintext" value="' + data['basic'][i].email + '" name="email[]" size="15">');
$('#inputs').append('<label>Password:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].Pass +'" name="pass[]" size="5">');
$('#inputs').append('<label>Status:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].status +'" name="pass[]" size="5">');
$('#inputs').append('<label>Acc. Address:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].Accno +'" name="pass[]" size="44">');
$('#inputs').append('<label>Balance:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].bal +'" name="pass[]" size="10">');
}
for( var j = 0; j<data['detail'].length; j++) {
var List = ["<tr><td>" + data['detail'][i].type + "</td><td>"+data['detail'][i].DB+"</td><td>"+data['detail'][i].LD+"</td><td>"+data['detail'][i].Prof+"</td><td>"+data['detail'][i].Server_stat+"</td></tr>"];
}
$("#bodywallet").append(List);
},
});
});
})
html code
<table class="table" id="wallet">
<thead class=" text-primary">
<tr>
<th class="text-left">Type</th>
<th class="text-left">Date_Bought</th>
<th class="text-left">Expires</th>
<th class="text-left">Profit</th>
<th class="text-left">Status</th>
</tr>
</thead>
<tbody class="text-left" id="bodywallet" >
</tbody>
</table>
this is what my data should be display on table
but it is displaying the first record only
i have checked json is bringing all the required data. what i have done wrong what is the mistake.any help will be appreciated. thanks
php code
while($row2 = mysqli_fetch_array($alEmailrslt))
{
$json_array['detail'][] = $row2;
}
echo json_encode($json_array);
You are putting everything in an array I and appending it every round.
You should use something like this instead:
success: function (data) {
var data = JSON.parse(data);
var list = []; // only one array
for (var j = 0; j < data['detail'].length; j++) {
// push to this array instead of overwriting the variable
list.push("<tr><td>" + data['detail'][j].type + "</td><td>" + data['detail'][j].DB + "</td><td>" + data['detail'][j].LD + "</td><td>" + data['detail'][j].Prof + "</td><td>" + data['detail'][j].Server_stat + "</td></tr>");
}
// update html once
// the join "glues" all parts of the array into one string
$("#bodywallet").append(list.join());
}
I think your list is not getting updated every time and the simplest approach would be, please find below code snippet:
$(document).ready(function() {
this.json = {
"Students": [{
"id": "1",
"hometown": "London",
"gender": "Male",
"GPA": "8",
"name": "Lee",
},
{
"id": "2",
"hometown": "NY",
"gender": "Male",
"GPA": "9",
"name": "Shaldon",
}, {
"id": "3",
"hometown": "Paris",
"gender": "Female",
"GPA": "7",
"name": "Julie",
}
]
};
this.renderTable = function(Students) {
var tbody = document.getElementById('tbody');
tbody.innerHTML = "";
for (var i = 0; i < Students.length; i++) {
var tr = "<tr>";
tr += "<td>ID</td>" + "<td>" + Students[i].id + "</td></tr>";
tr += "<td>HomeTown</td>" + "<td>" + Students[i].hometown + "</td></tr>";
tr += "<td>Gender</td>" + "<td>" + Students[i].gender + "</td></tr>";
tr += "<td>GPA</td>" + "<td>" + Students[i].GPA + "</td></tr>";
tr += "<td>NAME</td>" + "<td>" + Students[i].name + "</td></tr>";
tr += "<hr>";
tbody.innerHTML += tr;
}
}
this.renderTable(this.json.Students);
console.log(this.json.Students);
//code for filtering//
this.Filter = function() {
var search = document.getElementById('search');
var category = document.getElementById('category');
var filteredObj = this.json.Students;
filteredObj = $.map(this.json.Students, function(val, key) {
if (search.value === val[category.value]) return val;
});
filteredObj.length>0 ? this.renderTable(filteredObj) : this.renderTable(this.json.Students);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<p></p>
<input id="search" type="search">
<select id = "category">
<option value = "select">select</option>
<option value = "id">ID</option>
<option value = "hometown">HomeTown</option>
<option value = "gender">Gender</option>
<option value = "GPA">GPA</option>
<option value = "name">NAME</option>
</select>
<button onclick="Filter()">Filter</button>
<table>
<tbody id="tbody"></tbody>
</table>

Make entire table editable and saving the changes on click

I'm trying to make an editable table such that when the user clicks on the 'edit' button, every table data cell get placed inside an input form that the user can type in and change the information. Once the user is done, they may click the edit button again so that all of the input fields go away and the changes made are saved and displayed on the table.
I have made it so that every single data in every table data cell gets placed inside an input field when the user clicks the single 'edit' button. However, I'm having a really rough time trying to figure out how to remove the input boxes and display all the updated table cells. I was thinking of placing "contenteditable" withing every td and changing it to true/false would work, but I couldn't figure it out.
I'm using local storage for this, but I just need help on this one thing. Any help would be greatly appreciated.
var retrieveContacts = localStorage.getItem("contacts");
var newVariable = JSON.parse(retrieveContacts);
var isEdit = 0; // is the table in edit mode? 0- false 1- true
// set to 0 (false) by default
$.each(newVariable, function(){
$('#tableStyles').append('<tr>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].email + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].firstname + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].lastname + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].prefix + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].title + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].company + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].phone + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].fax + '</td>' +
'</tr>');
i++;
});
$('#createCont').click(function(){
var newRow = "<tr style='height: 35px;'><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>";
$('#tableStyles').append(newRow);
newVariable.push({"email": "",
"firstname": "",
"lastname": "",
"prefix": "",
"title": "",
"company": "",
"phone": "",
"fax": ""});
localStorage.setItem("contacts", JSON.stringify(newVariable));
});
$('#editCont').click(function(){
if(isEdit == 0){
var j = 0;
var trCount = 2; // up to newVariable.length+1
var tdCount = 1; // up to 8
for(trCount; trCount < newVariable.length+2; trCount++){
for(tdCount; tdCount < 9; tdCount++){
var testing1 = $("tr:nth-child(" + trCount + ")").children("td:nth-child(" + tdCount + ")");
var testing2 = testing1.html("<input type='text' value='" + testing1.html() + "'/>");
}
tdCount = 1;
}
trCount = 2;
tdCount = 1;
isEdit = 1;
//console.log("isEdit set to 1");
} else if(isEdit == 1) { // if the edit button is clicked and we are already editing the form,
// then we have take out the input boxes and save all changes.
for(trCount; trCount < newVariable.length+2; trCount++){
for(tdCount; tdCount < 9; tdCount++){
var testing1 = $("tr:nth-child(" + trCount + ")").children("td:nth-child(" + tdCount + ")");
}
tdCount = 1;
}
isEdit = 0;
//console.log("isEdit set to " + isEdit);
}
});
I would like to offer you a better solution. You can place the input field directly into the table cells and use the readonly attribute to set it editable.
Here is the code:
document.getElementById("edit").addEventListener("click", function() {
var fields = document.querySelectorAll("table input[type='text']");
for (var i = 0; i < fields.length; i++) {
fields[i].readOnly = false;
}
document.getElementById("save").style.display = "inline-block";
});
document.getElementById("save").addEventListener("click", function() {
var data = {};
data.name = document.getElementById("name").value;
data.email = document.getElementById("email").value;
// window.localStorage.formData = JSON.stringify(data);
// localStorage will not work in this snippet editor
// uncomment it in your code
var fields = document.querySelectorAll("table input[type='text']");
for (var i = 0; i < fields.length; i++) {
fields[i].readOnly = true;
}
document.getElementById("save").style.display = "none";
});
table input[type="text"] {
/* place any styling here */
}
table input[type="text"]:read-only {
border: none;
}
#save {
display: none;
}
<form>
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="name" value="Some Name" readonly /></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" id="email" value="Email address" readonly /></td>
</tr>
</table>
<input type="button" id="edit" value="Edit" />
<input type="button" id="save" value="Save" />
</form>
Please, tell me if it works for you!

Paragraph numbers changing HTML JAVASCRIPT

I'm working with list which elements can be added with JS by the following code:
function getMovementButtons(size, articleId, articleTitle, articleType){
var lowerArticleType = articleType.toLowerCase();
var html = '<div>'+
'<span style="vertical-align: top">'+ size +
'<span style="vertical-align: top">.</span> '+
'</span>'+
'<span style="vertical-align: top" class="'+lowerArticleType+'-title displaying-'+lowerArticleType+'-id' + articleId +'">' + articleTitle + '</span>' +
'<input class="'+lowerArticleType+'-button-delete" type="button" value="' + '<%= LanguageUtil.get(pageContext, "global.action.delete")%>' + '" onclick="removeArticle(this,\''+articleType+'\')"/>' +
'<div class="'+lowerArticleType+'-div-move"><input class="'+lowerArticleType+'-button-up" type="button" value="" onclick="moveArticleUp(this,\''+articleType+'\')"/>' +
'<input class="'+lowerArticleType+'-button-down" type="button" value="" onclick="moveArticleDown(this,\''+articleType+'\')"/>' +
'</div>'+
'</div>';
return html;
I have a function removeArticleLine.
function removeArticleLine(button) {
var parentDiv = button.parentNode
var articleListDiv = parentDiv.parentNode;
articleListDiv.removeChild(parentDiv);
}
There is a problem, because if I delete an object paragraphs don't change their numbers. I would ask you to give me a hint how can I change these numbers with JS.
I'm adding working functions which can help us. It's moving everything properly:
function moveArticleUp(button, articleType) {
var articleDiv = button.parentNode.parentNode;
var parentDiv = articleDiv.parentNode;
var prevArticleDiv = articleDiv.previousElementSibling;
if (prevArticleDiv && prevArticleDiv.tagName == 'DIV') {
var articleIdValue = getArticleIdValue(articleType);
var ids = articleIdValue.split(',');
var articleId = getArticleIdFromArticleDiv(articleDiv, articleType);
var articleIdIndex = ids.indexOf(articleId);
swapPosition(ids, articleIdIndex, articleIdIndex - 1);
setArticleIdValue(articleType, ids.join());
removedArticleDiv = parentDiv.removeChild(articleDiv);
parentDiv.insertBefore(removedArticleDiv, prevArticleDiv);
console.log(articleIdIndex);
prevArticleDiv.firstElementChild.innerHTML = articleIdIndex + 1 + '<span style="vertical-align: top">.</span> ';
articleDiv.firstElementChild.innerHTML = articleIdIndex + '<span style="vertical-align: top">.</span> ';
}
}
function moveArticleDown(button, articleType) {
var articleDiv = button.parentNode.parentNode;
var parentDiv = articleDiv.parentNode;
var nextArticleDiv = articleDiv.nextElementSibling;
if (nextArticleDiv) {
var articleIdValue = getArticleIdValue(articleType);
console.log(articleIdValue);
var ids = articleIdValue.split(',');
var articleId = getArticleIdFromArticleDiv(articleDiv, articleType);
console.log(articleId);
var articleIdIndex = ids.indexOf(articleId);
console.log(articleIdIndex);
swapPosition(ids, articleIdIndex, articleIdIndex + 1);
setArticleIdValue(articleType, ids.join());
console.log(ids.join());
removedArticleDiv = parentDiv.removeChild(nextArticleDiv);
parentDiv.insertBefore(removedArticleDiv, articleDiv);
console.log(nextArticleDiv.firstElementChild.innerHTML);
console.log(articleDiv.firstElementChild.innerHTML);
nextArticleDiv.firstElementChild.innerHTML = articleIdIndex + 1 + '<span style="vertical-align: top">.</span> ';
articleDiv.firstElementChild.innerHTML = articleIdIndex + 2 + '<span style="vertical-align: top">.</span> ';
}
}
Let me add two screenshots of the displayed table:
http://imgur.com/a/EOfkk
http://imgur.com/a/R9oru
After you remove a line you should loop the array of elements and assign new numbers for them. The code was not tested, but it should works
function removeArticleLine(button) {
var parentDiv = button.parentNode;
// getting the number of deleting div
var divNumber = parseInt(parentDiv.firstChild.textContent);
var articleListDiv = parentDiv.parentNode;
articleListDiv.removeChild(parentDiv);
// we need to loop elements after deleted div, because elements before did not change theit number
for (var i = 0 || divNumber; i < articleListDiv.children.length; i++) {
//changing number
articleListDiv.children[i].firstElementChild.innerHTML = (i + 1) + '<span style="vertical-align: top">.</span> ';
}
}

Total required in javascript

I have a query in javascript.. Please check the below image
In Above image :
First Input Box is Description
2nd Input Box is Qty
3rd is Value
I have got total qty using below script onchange of textbox :
function findTotal(){
var total = 0;
var $changeInputs = $('input.qtyValue');
$changeInputs.each(function(idx, el) {
total += Number($(el).val());
});
$('.total').text(total);
$("#totalvval").val(total);
}
I have got total Value using below :
function qfindTotal(){
var total = 0;
var $changeInputs = $('input.qqtyValue');
$changeInputs.each(function(idx, el) {
total += Number($(el).val());
});
$('.qtotal').text(total);
$("#totalqval").val(total);
if(total>10000){
alert("Amount should not be greater than 10000");
}
}
My query is that we need total of qty x value + qty x value + qty x value =total
You can try something like this:
Fiddle
Code
function createHTML() {
var html = "";
for (var i = 0; i < 3; i++) {
html += "<input type='text' class='qty' id='txtQty_" + i + "' onblur='updateTotal()' />";
html += "<input type='text' class='cost' id='txtQty_" + i + "' onblur='updateTotal()'/>";
html += "<br/>"
}
html += "Qty Total: <span id='qty_total'>0</span>";
html += "Cost Total: <span id='cost_total'>0</span>";
document.getElementById("content").innerHTML = html
}
function updateTotal() {
var qty = document.getElementsByClassName("qty");
var cost = document.getElementsByClassName("cost");
var total_qty = 0;
var total_cost = 0;
for (var i = 0; i < qty.length; i++) {
if (qty[i].value && cost[i].value) {
total_cost += qty[i].value * cost[i].value;
total_qty += parseInt(qty[i].value);
}
}
document.getElementById("qty_total").innerHTML = total_qty;
document.getElementById("cost_total").innerHTML = total_cost;
}
(function() {
createHTML();
})()
<div id="content"></div>

Create table with jQuery - append

I have on page div:
<div id="here_table"></div>
and in jquery:
for(i=0;i<3;i++){
$('#here_table').append( 'result' + i );
}
this generating for me:
<div id="here_table">
result1 result2 result3 etc
</div>
I would like receive this in table:
<div id="here_table">
<table>
<tr><td>result1</td></tr>
<tr><td>result2</td></tr>
<tr><td>result3</td></tr>
</table>
</div>
I doing:
$('#here_table').append( '<table>' );
for(i=0;i<3;i++){
$('#here_table').append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
$('#here_table').append( '</table>' );
but this generate for me:
<div id="here_table">
<table> </table> !!!!!!!!!!
<tr><td>result1</td></tr>
<tr><td>result2</td></tr>
<tr><td>result3</td></tr>
</div>
Why? how can i make this correctly?
LIVE: http://jsfiddle.net/n7cyE/
This line:
$('#here_table').append( '<tr><td>' + 'result' + i + '</td></tr>' );
Appends to the div#here_table not the new table.
There are several approaches:
/* Note that the whole content variable is just a string */
var content = "<table>"
for(i=0; i<3; i++){
content += '<tr><td>' + 'result ' + i + '</td></tr>';
}
content += "</table>"
$('#here_table').append(content);
But, with the above approach it is less manageable to add styles and do stuff dynamically with <table>.
But how about this one, it does what you expect nearly great:
var table = $('<table>').addClass('foo');
for(i=0; i<3; i++){
var row = $('<tr>').addClass('bar').text('result ' + i);
table.append(row);
}
$('#here_table').append(table);
Hope this would help.
You need to append the tr inside the table so I updated your selector inside your loop and removed the closing table because it is not necessary.
$('#here_table').append( '<table />' );
for(i=0;i<3;i++){
$('#here_table table').append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
The main problem was that you were appending the tr to the div here_table.
Edit: Here is a JavaScript version if performance is a concern. Using document fragment will not cause a reflow for every iteration of the loop
var doc = document;
var fragment = doc.createDocumentFragment();
for (i = 0; i < 3; i++) {
var tr = doc.createElement("tr");
var td = doc.createElement("td");
td.innerHTML = "content";
tr.appendChild(td);
//does not trigger reflow
fragment.appendChild(tr);
}
var table = doc.createElement("table");
table.appendChild(fragment);
doc.getElementById("here_table").appendChild(table);
When you use append, jQuery expects it to be well-formed HTML (plain text counts). append is not like doing +=.
You need to make the table first, then append it.
var $table = $('<table/>');
for(var i=0; i<3; i++){
$table.append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
$('#here_table').append($table);
Or do it this way to use ALL jQuery. The each can loop through any data be it DOM elements or an array/object.
var data = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'];
var numCols = 1;
$.each(data, function(i) {
if(!(i%numCols)) tRow = $('<tr>');
tCell = $('<td>').html(data[i]);
$('table').append(tRow.append(tCell));
});
​
http://jsfiddle.net/n7cyE/93/
To add multiple columns and rows, we can also do a string concatenation. Not the best way, but it sure works.
var resultstring='<table>';
for(var j=0;j<arr.length;j++){
//array arr contains the field names in this case
resultstring+= '<th>'+ arr[j] + '</th>';
}
$(resultset).each(function(i, result) {
// resultset is in json format
resultstring+='<tr>';
for(var j=0;j<arr.length;j++){
resultstring+='<td>'+ result[arr[j]]+ '</td>';
}
resultstring+='</tr>';
});
resultstring+='</table>';
$('#resultdisplay').html(resultstring);
This also allows you to add rows and columns to the table dynamically, without hardcoding the fieldnames.
Here is what you can do: http://jsfiddle.net/n7cyE/4/
$('#here_table').append('<table></table>');
var table = $('#here_table').children();
for(i=0;i<3;i++){
table.append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
Best regards!
Following is done for multiple file uploads using jquery:
File input button:
<div>
<input type="file" name="uploadFiles" id="uploadFiles" multiple="multiple" class="input-xlarge" onchange="getFileSizeandName(this);"/>
</div>
Displaying File name and File size in a table:
<div id="uploadMultipleFilediv">
<table id="uploadTable" class="table table-striped table-bordered table-condensed"></table></div>
Javascript for getting the file name and file size:
function getFileSizeandName(input)
{
var select = $('#uploadTable');
//select.empty();
var totalsizeOfUploadFiles = "";
for(var i =0; i<input.files.length; i++)
{
var filesizeInBytes = input.files[i].size; // file size in bytes
var filesizeInMB = (filesizeInBytes / (1024*1024)).toFixed(2); // convert the file size from bytes to mb
var filename = input.files[i].name;
select.append($('<tr><td>'+filename+'</td><td>'+filesizeInMB+'</td></tr>'));
totalsizeOfUploadFiles = totalsizeOfUploadFiles+filesizeInMB;
//alert("File name is : "+filename+" || size : "+filesizeInMB+" MB || size : "+filesizeInBytes+" Bytes");
}
}
Or static HTML without the loop for creating some links (or whatever). Place the <div id="menu"> on any page to reproduce the HTML.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML Masterpage</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
function nav() {
var menuHTML= '<ul><li>link 1</li></ul><ul><li>link 2</li></ul>';
$('#menu').append(menuHTML);
}
</script>
<style type="text/css">
</style>
</head>
<body onload="nav()">
<div id="menu"></div>
</body>
</html>
I wrote rather good function that can generate vertical and horizontal tables:
function generateTable(rowsData, titles, type, _class) {
var $table = $("<table>").addClass(_class);
var $tbody = $("<tbody>").appendTo($table);
if (type == 2) {//vertical table
if (rowsData.length !== titles.length) {
console.error('rows and data rows count doesent match');
return false;
}
titles.forEach(function (title, index) {
var $tr = $("<tr>");
$("<th>").html(title).appendTo($tr);
var rows = rowsData[index];
rows.forEach(function (html) {
$("<td>").html(html).appendTo($tr);
});
$tr.appendTo($tbody);
});
} else if (type == 1) {//horsantal table
var valid = true;
rowsData.forEach(function (row) {
if (!row) {
valid = false;
return;
}
if (row.length !== titles.length) {
valid = false;
return;
}
});
if (!valid) {
console.error('rows and data rows count doesent match');
return false;
}
var $tr = $("<tr>");
titles.forEach(function (title, index) {
$("<th>").html(title).appendTo($tr);
});
$tr.appendTo($tbody);
rowsData.forEach(function (row, index) {
var $tr = $("<tr>");
row.forEach(function (html) {
$("<td>").html(html).appendTo($tr);
});
$tr.appendTo($tbody);
});
}
return $table;
}
usage example:
var title = [
'مساحت موجود',
'مساحت باقیمانده',
'مساحت در طرح'
];
var rows = [
[number_format(data.source.area,2)],
[number_format(data.intersection.area,2)],
[number_format(data.deference.area,2)]
];
var $ft = generateTable(rows, title, 2,"table table-striped table-hover table-bordered");
$ft.appendTo( GroupAnalyse.$results );
var title = [
'جهت',
'اندازه قبلی',
'اندازه فعلی',
'وضعیت',
'میزان عقب نشینی',
];
var rows = data.edgesData.map(function (r) {
return [
r.directionText,
r.lineLength,
r.newLineLength,
r.stateText,
r.lineLengthDifference
];
});
var $et = generateTable(rows, title, 1,"table table-striped table-hover table-bordered");
$et.appendTo( GroupAnalyse.$results );
$('<hr/>').appendTo( GroupAnalyse.$results );
example result:
A working example using the method mentioned above and using JSON to represent the data. This is used in my project of dealing with ajax calls fetching data from server.
http://jsfiddle.net/vinocui/22mX6/1/
In your html:
< table id='here_table' >< /table >
JS code:
function feed_table(tableobj){
// data is a JSON object with
//{'id': 'table id',
// 'header':[{'a': 'Asset Tpe', 'b' : 'Description', 'c' : 'Assets Value', 'd':'Action'}],
// 'data': [{'a': 'Non Real Estate', 'b' :'Credit card', 'c' :'$5000' , 'd': 'Edit/Delete' },... ]}
$('#' + tableobj.id).html( '' );
$.each([tableobj.header, tableobj.data], function(_index, _obj){
$.each(_obj, function(index, row){
var line = "";
$.each(row, function(key, value){
if(0 === _index){
line += '<th>' + value + '</th>';
}else{
line += '<td>' + value + '</td>';
}
});
line = '<tr>' + line + '</tr>';
$('#' + tableobj.id).append(line);
});
});
}
// testing
$(function(){
var t = {
'id': 'here_table',
'header':[{'a': 'Asset Tpe', 'b' : 'Description', 'c' : 'Assets Value', 'd':'Action'}],
'data': [{'a': 'Non Real Estate', 'b' :'Credit card', 'c' :'$5000' , 'd': 'Edit/Delete' },
{'a': 'Real Estate', 'b' :'Property', 'c' :'$500000' , 'd': 'Edit/Delete' }
]};
feed_table(t);
});
As for me, this approach is prettier:
String.prototype.embraceWith = function(tag) {
return "<" + tag + ">" + this + "</" + tag + ">";
};
var results = [
{type:"Fiat", model:500, color:"white"},
{type:"Mercedes", model: "Benz", color:"black"},
{type:"BMV", model: "X6", color:"black"}
];
var tableHeader = ("Type".embraceWith("th") + "Model".embraceWith("th") + "Color".embraceWith("th")).embraceWith("tr");
var tableBody = results.map(function(item) {
return (item.type.embraceWith("td") + item.model.toString().embraceWith("td") + item.color.embraceWith("td")).embraceWith("tr")
}).join("");
var table = (tableHeader + tableBody).embraceWith("table");
$("#result-holder").append(table);
i prefer the most readable and extensible way using jquery.
Also, you can build fully dynamic content on the fly.
Since jquery version 1.4 you can pass attributes to elements which is, imho, a killer feature.
Also the code can be kept cleaner.
$(function(){
var tablerows = new Array();
$.each(['result1', 'result2', 'result3'], function( index, value ) {
tablerows.push('<tr><td>' + value + '</td></tr>');
});
var table = $('<table/>', {
html: tablerows
});
var div = $('<div/>', {
id: 'here_table',
html: table
});
$('body').append(div);
});
Addon: passing more than one "html" tag you've to use array notation like:
e.g.
var div = $('<div/>', {
id: 'here_table',
html: [ div1, div2, table ]
});
best Rgds.
Franz
<table id="game_table" border="1">
and Jquery
var i;
for (i = 0; ii < 10; i++)
{
var tr = $("<tr></tr>")
var ii;
for (ii = 0; ii < 10; ii++)
{
tr.append(`<th>Firstname</th>`)
}
$('#game_table').append(tr)
}
this is most better
html
<div id="here_table"> </div>
jQuery
$('#here_table').append( '<table>' );
for(i=0;i<3;i++)
{
$('#here_table').append( '<tr>' + 'result' + i + '</tr>' );
for(ii=0;ii<3;ii++)
{
$('#here_table').append( '<td>' + 'result' + i + '</tr>' );
}
}
$('#here_table').append( '</table>' );
It is important to note that you could use Emmet to achieve the same result. First, check what Emmet can do for you at https://emmet.io/
In a nutshell, with Emmet, you can expand a string into a complexe HTML markup as shown in the examples below:
Example #1
ul>li*5
... will produce
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
Example #2
div#header+div.page+div#footer.class1.class2.class3
... will produce
<div id="header"></div>
<div class="page"></div>
<div id="footer" class="class1 class2 class3"></div>
And list goes on. There are more examples at https://docs.emmet.io/abbreviations/syntax/
And there is a library for doing that using jQuery. It's called Emmet.js and available at https://github.com/christiansandor/Emmet.js
Here the below code helps to generate responsive html table
#javascript
(function($){
var data = [{
"head 1": "row1 col 1",
"head 2": "row1 col 2",
"head 3": "row1 col 3"
}, {
"head 1": "row2 col 1",
"head 2": "row2 col 2",
"head 3": "row2 col 3"
}, {
"head 1": "row3 col 1",
"head 2": "row3 col 2",
"head 3": "row3 col 3"
}];
for (var i = 0; i < data.length; i++) {
var accordianhtml = "<button class='accordion'>" + data[i][small_screen_heading] + "<span class='arrow rarrow'>→</span><span class='arrow darrow'>↓</span></button><div class='panel'><p><table class='accordian_table'>";
var table_row = null;
var table_header = null;
for (var key in data[i]) {
accordianhtml = accordianhtml + "<tr><th>" + key + "</th><td>" + data[i][key] + "</td></tr>";
if (i === 0 && true) {
table_header = table_header + "<th>" + key + "</th>";
}
table_row = table_row + "<td>" + data[i][key] + "</td>"
}
if (i === 0 && true) {
table_header = "<tr>" + table_header + "</tr>";
$(".mv_table #simple_table").append(table_header);
}
table_row = "<tr>" + table_row + "</tr>";
$(".mv_table #simple_table").append(table_row);
accordianhtml = accordianhtml + "</table></p></div>";
$(".mv_table .accordian_content").append(accordianhtml);
}
}(jquery)
Here we can see the demo responsive html table generator
let html = '';
html += '<table class="tblWay" border="0" cellpadding="5" cellspacing="0" width="100%">';
html += '<tbody>';
html += '<tr style="background-color:#EEEFF0">';
html += '<td width="80"> </td>';
html += '<td><b>Shipping Method</b></td>';
html += '<td><b>Shipping Cost</b></td>';
html += '<td><b>Transit Time</b></td>';
html += '</tr>';
html += '</tbody>';
html += '</table>';
$('.product-shipping-more').append(html);

Categories

Resources