Displaying Javascript Array in pre-coded HTML? - javascript

I need to display a list of 100+ football player numbers, names, weight, age, and heights. I would rather not copy/paste the same exact div I have set up and change them manually. I was wondering if there is a way to display each set of data in the html layout I already coded? The only thing I can find on google is Javascript generating it's own table. Here is an example:
Here's the array:
var playerArray = [
["#25","Player1", "Weight1", "Height1", "Age1", "Position1"],
["#99","Player2", "Weight2", "Height2", "Age2", "Position2"],
["#77","Player3", "Weight3", "Height3", "Age3", "Position3"],
["#63","Player4", "Weight4", "Height4", "Age4", "Position4"],
["#43","Player5", "Weight5", "Height5", "Age5", "Position5"],
];
and here is my html where I want the data displayed:
<div class="rosterlist">
<div class="p_name">[[NUMBER]] <span class="light_text2">/ [[NAME]]</span></div>
<div class="roster_line_2"><div class="p_pos">[[POSITION]]</div><div class="p_height">[[HEIGHT]]</div><div class="p_grade">[[AGE]]</div><div class="p_weight">[[WEIGHT]]</div></div>
</div>
If it's not possible, just let me know and I'll get to my copying and pasting:(

This is best solved through data binding and templating.
I recommend using a template based framework like KnockoutJS.
This will give you the ability to specify a single entry that gets repeated for each entry
Link: http://knockoutjs.com/

As Stano states, this is straight-forward to do without a library:
var i, k, html = '', line = '';
var template = ''+
'<div class="rosterlist">' +
'<div class="p_name">[[0]] <span class="light_text2">/ [[1]]</span></div>'+
'<div class="roster_line_2">'+
'<div class="p_pos">[[5]]</div>'+
'<div class="p_height">[[3]]</div>'+
'<div class="p_grade">[[4]]</div>'+
'<div class="p_weight">[[2]]</div>'+
'</div>'+
'</div>'+
'';
var data = [
["#25","Player1", "Weight1", "Height1", "Age1", "Position1"],
["#99","Player2", "Weight2", "Height2", "Age2", "Position2"],
["#77","Player3", "Weight3", "Height3", "Age3", "Position3"],
["#63","Player4", "Weight4", "Height4", "Age4", "Position4"],
["#43","Player5", "Weight5", "Height5", "Age5", "Position5"],
];
for( i=0; i<data.length; i++ ) {
line = template;
for( k=0; k<data[i].length; k++ ) {
line = line.replace('[['+k+']]', data[i][k]);
}
html += line;
}
document.getElementById('output').innerHTML = html;
And in your markup:
<div id="output"></div>

I'm personally a fan of Handlebars
Here's a fiddle
http://jsfiddle.net/BZ2nZ/
the HTML:
<div id="container"></div>
<script type="text/x-handlebars-template" id="rosterlistTemplate">
<div class="rosterlist">
{{#each this}}
<div class="p_name">{{number}} <span class="light_text2">/ {{name}}</span>
</div>
<div class="roster_line_2">
<div class="p_pos">{{position}}</div>
<div class="p_height">{{height}}</div>
<div class="p_grade">{{age}}</div>
<div class="p_weight">{{weight}}</div>
</div>
{{/each}}
</div>
</script>
The data:
var playerArray = [
["#25","Player1", "Weight1", "Height1", "Age1", "Position1"],
["#99","Player2", "Weight2", "Height2", "Age2", "Position2"],
["#77","Player3", "Weight3", "Height3", "Age3", "Position3"],
["#63","Player4", "Weight4", "Height4", "Age4", "Position4"],
["#43","Player5", "Weight5", "Height5", "Age5", "Position5"],
];
Convert the data:
var data = _(playerArray).map(function(playerInfo){
return _.object(['number','name','weight', 'height', 'age', 'position'], playerInfo);
});
Putting the template to use :
var template = Handlebars.compile($('#rosterlistTemplate').html());
$('#container').html(template(data));
I'm using underscore to convert the format of the data you have into something like this
[
{number: xx, name: xx, weight: xx, height: xx, age: xx, position: xx},
{number: xx, name: xx, weight: xx, height: xx, age: xx, position: xx},
{number: xx, name: xx, weight: xx, height: xx, age: xx, position: xx},
]
If you can get the json in that format then you don't need underscore and can skip the 'convert data' step altogether.

Working jsFiddle Demo
JavaScript
<script>
var playerArray = [
["#25","Player1", "Weight1", "Height1", "Age1", "Position1"],
["#99","Player2", "Weight2", "Height2", "Age2", "Position2"],
["#77","Player3", "Weight3", "Height3", "Age3", "Position3"],
["#63","Player4", "Weight4", "Height4", "Age4", "Position4"],
["#43","Player5", "Weight5", "Height5", "Age5", "Position5"],
];
window.onload = function () {
var template = document.getElementById('template').innerHTML;
var list = document.getElementById('list');
for (var i = 0, l = playerArray.length; i < l; i++) {
var values = {
'NUMBER': playerArray[i][0],
'NAME': playerArray[i][1],
'WEIGHT': playerArray[i][2],
'HEIGHT': playerArray[i][3],
'AGE': playerArray[i][4],
'POSITION': playerArray[i][5],
};
var t = template;
for (var p in values) {
t = t.replace('[[' + p + ']]', values[p]);
}
list.innerHTML += t;
}
};
</script>
HTML
<div id="list"></div>
<script id="template" type="text/html">
<div class="rosterlist">
<div class="p_name">[[NUMBER]] <span class="light_text2">/ [[NAME]]</span></div>
<div class="roster_line_2"><div class="p_pos">[[POSITION]]</div><div class="p_height">[[HEIGHT]]</div><div class="p_grade">[[AGE]]</div><div class="p_weight">[[WEIGHT]]</div></div>
</div>
</script>

You can traverse the array like this:
var str = '';
var len = playerArray.length;
for (var i = 0; i < len; i++) {
str += '<div class="p_name">' + playerArray[i][0] +
'/ <span class="light_text2">' + playerArray[i][1] + '</span> \
</div> \
<div class="roster_line_2"> \
<div class="p_pos">' + playerArray[i][5] + '</div> \
<div class="p_height">' + playerArray[i][3] + '</div> \
<div class="p_grade">' + playerArray[i][4] + '</div> \
<div class="p_weight">' + playerArray[i][2] + '</div> \
</div>';
}
document.getElementById('rosterlist').innerHTML = str;
Full javascript code here: http://jsfiddle.net/VuKmv/ (compatible also with IE6+)

Related

JSON result value as key in JavaScript/jQuery

I have a JSON result where I want to create an accordion menu, I want one value of similar results as title of those similar rows, please check below to see what I did.
Suppose a I have below JSON object
var items = [
{label: "TY2021H", name: "10-Yr T-Notes", value: "TY2021H"},
{label: "TY2020Z-TY2021H", name: "10-Yr T-Notes Spread", value: "TY2020Z-TY2021H"},
{label: "TY2021H-TY2021M", name: "10-Yr T-Notes Spread", value: "TY2021H-TY2021M"},
{label: "TY2020Z-2*TY2021H+TY2021M", name: "10-Yr T-Notes Butterfly", value: "TY2020Z-2*TY2021H+TY2021M"}]
The related part of my JS code is as follow:
var myUL = $("#accordion");
myUL.empty();
var currentName = "";
for (var i = 0; i <= items.length - 1; i++) {
var label = items[i].label;
if (items[i].name != currentName) {
currentName = items[i].name;
list +=
'<a href="#demo' +
i +
'" class="list-group-item list-group-item-info" data-toggle="collapse" data-parent="#accordion">' +
currentName +
' <span id="opnClsSign" class="glyphicon glyphicon-menu-down"></span></a>';
list += '<div class="collapse in" id="demo' + i + '">';
}
list += '' + label + "";
}
list += "</div>";
myUL.append(list);
Part of my HTML div
<div class="list-group panel" id="accordion"></div>
Result I get now
What I expect
Code indentation can help in a situation like this. Your last two lines should be inside the loop for the code to make sense. In every iteration, you must close the div and add the code to myUL:
var items = [
{label: "TY2021H", name: "10-Yr T-Notes", value: "TY2021H"},
{label: "TY2020Z-TY2021H", name: "10-Yr T-Notes Spread", value: "TY2020Z-TY2021H"},
{label: "TY2021H-TY2021M", name: "10-Yr T-Notes Spread", value: "TY2021H-TY2021M"},
{label: "TY2020Z-2*TY2021H+TY2021M", name: "10-Yr T-Notes Butterfly", value: "TY2020Z-2*TY2021H+TY2021M"}]
var myUL = $("#accordion");
myUL.empty();
var currentName = "";
for (var i = 0; i <= items.length - 1; i++) {
var label = items[i].label;
var list = '';
if (items[i].name != currentName) {
currentName = items[i].name;
list +=
'<a href="#demo' +
i +
'" class="list-group-item list-group-item-info" data-toggle="collapse" data-parent="#accordion">' +
currentName +
' <span id="opnClsSign" class="glyphicon glyphicon-menu-down"></span></a>';
list += '<div class="collapse in" id="demo' + i + '">';
}
list += '' + label + "";
list += "</div>";
myUL.append(list);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-group panel" id="accordion"></div>
Also, you needed to define list.
I resolved the issue my self, and I have added the final source code into this pen:
[https://codepen.io/rafihaidari/pen/ExyBGVK]

For Loop with two array in javascript

I am new in js and have this problem. I have two arrays and like to achieve this layout by using for loop. I do not know how to write this to achieve it. Here is my code. Please help.
var html ='';
var option = ['meal', 'drink'];
var option_type = ['big', 'medium', 'small', 'big', 'medium'];
for (var i in option){
for ( var j in option_type){
html += '<div>'+ option[i] + '</div>'+'<p>'+option_type[j]+'</p>';
}
}
.(class).html(html);
You can use for like:
var html = '';
var option = ['meal', 'drink'];
var option_type = ['big', 'medium', 'small'];
for (i = 0; i < option.length; i++) {
html += '<div>' + option[i] + '</div>'; //Add option here (header)
for (j = 0; j < option_type.length; j++) {
html += '<p>' + option_type[j] + '</p>'; //Add option_type
}
}
$('body').html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
An object data structure is better for representing what you want (at least based on the screenshot)
var options = {
meal: ['big', 'medium', 'small'],
drink: ['big', 'medium']
}
var html = Object.keys(options).reduce((all, option) => {
var headerMarkup = `<div>${option}</div>`;
var itemsMarkup = options[option].map(item => `<p>${item}</p>`).join('');
return `${all}${headerMarkup}${itemsMarkup}`;
}, '');
You can do something like this:
var html ='';
var option = [
['meal', 'big', 'medium', 'small'],
['drink', 'big', 'medium' ]
];
for (var i = 0; i < option.length; i++){
var option_type = option[i];
html += '<div>' + option_type[0] + '</div>';
for(var j = 1; j < option_type.length; j++) {
html += '<span>' + option_type[j] + '</span>';
}
}
document.getElementById('container').innerHTML=html;
#container span{
display:inline-block;
margin-right:10px;
border:1px solid #333;
padding:10px;
}
<div id="container"></div>
this is the direct answer to how to use nested for loops. But if you want to vary the option_types for each option, you will probably want to use an object as suggested by scetiner
var html ='';
var option = ['meal', 'drink'];
var option_type = ['big', 'medium', 'small'];
for (var i in option){
html += '<div><h1>'+ option[i] + "<h1>";
for ( var j in option_type){
html += '<p>'+option_type[j]+'</p>';
}
html += '</div>';
}
document.getElementById('container').innerHTML = html;
#container{
}
h1{
}
#container p{
display:inline-block;
margin:10px;
border:1px solid #333;
min-width: 100px;
padding:10px;
}
<div id='container'></div>
option_type is useless and not logical, try something like this
var html ='';
var option = {
'meal': [
'big',
'medium',
'small'
],
'drink': [
'big',
'medium'
]
};
for (var key in option){
html += '<div>'+ key + '</div>'
for ( var j of option[key]){
html += '<p>'+j+'</p>';
}
}
.(class).html(html);
Followin you approach here a full example: https://jsfiddle.net/57q39xre/17/
The key is:
for (var i in parent){
//parent code
for ( var j in child){
//parent and child code
}
//parent code
}
Each parent will iterate each child.

jQuery: How do I append an array item in a loop?

I'm trying to create a weather forecast page for a website.
I am using OpenWeatherMap to retrieve JSON data.
I want to loop through the "weather" array from the JSON, which contains objects that hold weather information.
This is the JSON shown in the console after using console.log (screenshot for readability):
Here is my jQuery/JavaScript:
$.getJSON("https://api.openweathermap.org/data/2.5/weather?lat=57.995221&lon=-6.761395&units=metric&APPID=myAPIkey", function(data){
var currWeather = [data.weather];
var len = currWeather.length;
for (i = 0; i > len; i++) {
$("#weather").append(currWeather[i].main);
$("#desc").append(currWeather[i].description);
}
var clouds = data.clouds.all;
$("#clouds").append(clouds);
var temp = data.main.temp;
$("#temp").append("Temperature: " + temp + "ยบC");
var humidity = data.main.humidity;
$("#humidity").append("Humidity: " + humidity + "%");
var pressure = data.main.pressure;
$("#pressure").append("Pressure: " + pressure);
console.log(data);
});
My HTML:
<div id="weatherBox">
<h2>Current Weather</h2>
<div id="mainWeather">
<div id="temp"></div></td>
<div id="weather"></div>
<div id="desc"></div>
<div id="icon"></div>
</div>
<br>
<div id="clouds"></div>
<div id="humidity"></div></td>
<div id="pressure"></div></td>
</div>
Basically, the only thing that isn't being displayed is the weather information. I have no errors or warnings in the console, am I doing this correctly?
Edit: I should add that in the json "weather" array, "0" and "1" are stored as strings. I tried to do:
$("#weather").append(currWeather[i.toString()].main);
Just to see if it would work. It did not.
A few things I found wrong with your code
You can access a property with dot notation or bracket notation so
either data.weather or data["weather"] not [data.weather]
your for loop should declare i as a var and it should be < the
length since you start at 0
The other properties should also be in the loop since they are in an
obj that is part of the array you are looping.
you accessed the other properties incorrectly it should be
weatherData[i].temp and not data.main.temp the main property is
a string, not an obj so you can't use a property accessor.
And of course you will have to do some additional formatting to make your display look pretty.
var data = {
weather: [{
main: "Drizzle",
description: "A light rain",
temp: 50,
humidity: 5,
pressure: 10
}, {
main: "Sunny",
description: "The sky is blue and so are you",
temp: 80,
humidity: 3,
pressure: 4
}]
}
var weatherData = data.weather;
var len = weatherData.length;
for (var i = 0; i < len; i++) {
var currWeather = weatherData[i];
//console.log(currWeather);
$("#weather").append(currWeather.main);
$("#desc").append(currWeather.description);
//var clouds = data.clouds.all;
//$("#clouds").append(clouds);
var temp = currWeather.temp;
//console.log(temp)
$("#temp").append(" Temperature: " + temp + "ยบC");
var humidity = currWeather.humidity;
$("#humidity").append(" Humidity: " + humidity + "%");
var pressure = currWeather.pressure;
$("#pressure").append(" Pressure: " + pressure);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weatherBox">
<h2>Current Weather</h2>
<div id="mainWeather">
<div id="temp"></div>
</td>
<div id="weather"></div>
<div id="desc"></div>
<div id="icon"></div>
</div>
<br>
<div id="clouds"></div>
<div id="humidity"></div>
</td>
<div id="pressure"></div>
</td>
</div>
Try this:
var currWeather = data.weather;
You're trying to storing data in the wrong place.
Here is a working example on jsBin: https://jsbin.com/bijoyoyofo/1/edit?html,js,output
Basically
var currWeather = [data.weather];
should be
var currWeather = data.weather;
and
for (var i = 0; i > len; i++) {
should be
for (i = 0; i < len; i++) {
I also added a paragraph in the div but that is up to you.
I adjusted your document to include the jQuery $(document).ready() function, using an API key I found on Github for open weather. You can access the weather array from data.weather, as you see below. You also had the loop written incorrectly, as you needed the var i to be less than the length, not greater than. Here is a working sample of your code.
$(document).ready(function(){
var myAPIkey = 'bd5e378503939ddaee76f12ad7a97608';
$.getJSON("https://api.openweathermap.org/data/2.5/weather?lat=57.995221&lon=-6.761395&units=metric&APPID="+myAPIkey, function(data){
var currWeather = data.weather;
for (i = 0; i < currWeather.length; i++) {
$("#weather").append(currWeather[i].main);
$("#desc").append(currWeather[i].description);
}
var clouds = data.clouds.all;
$("#clouds").append(clouds);
var temp = data.main.temp;
$("#temp").append("Temperature: " + temp + "ยบC");
var humidity = data.main.humidity;
$("#humidity").append("Humidity: " + humidity + "%");
var pressure = data.main.pressure;
$("#pressure").append("Pressure: " + pressure);
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weatherBox">
<h2>Current Weather</h2>
<div id="mainWeather">
<div id="temp"></div></td>
<div id="weather"></div>
<div id="desc"></div>
<div id="icon"></div>
</div>
<br>
<div id="clouds"></div>
<div id="humidity"></div></td>
<div id="pressure"></div></td>
</div>

Creating an array of containers using jquery

Template:
<Div id='Container'>
<div id='name'></div>
<div id='address'></div>
</div>
I want to then use this template by using a for loop to replicate it with the name and address within each container being different.
I don't want to recreate the whole template dynamically, as the template will never change.
So the output on the body should be like this:
<Div id='Container'>
<div id='name'></div>
<div id='address'></div>
</div>
<Div id='Container1'>
<div id='name'></div>
<div id='address'></div>
</div>
<Div id='Container2'>
<div id='name'></div>
<div id='address'></div>
</div>
Output on body:
Container:
Tom
sample address
Container 1:
Richard.
address 2
Container 3:
John
address 3
Try this:
for(var i = 0; i < 4; i++){
var container = document.createElement('div'),
name = document.createElement('div'),
address = document.createElement('div');
container.id = 'Container' + i;
name.className = 'name';
address.className = 'address';
container.appendChild(name);
container.appendChild(address);
document.body.appendChild(container);
}
//same thing using jQuery + people array for easy population
var people = [
{name: "Tom", address: "sample address"},
{name: "Richard", address: "address 2"},
{name: "John", address: "address 3"}
];
for(var i = 0, len = people.length; i < len; i++){
var container = $("<div id='Container" + i + "'><div class='name'>" + people[i].name + "</div><div class='address'>" + people[i].address + "</div></div>");
$('body').append(container);
}
The answer above is pure javascript and of course works, but you asked how to do it in jQuery, so here's a jQuery version using the $.each() method to iterate over an array of objects:
var mydata = [{"name": "Tom", "address": "123 Happy Land"},{"name": "Dick", "address": "456 Main Street"},{"name": "Harry", "address": "789 End of the World"}]
$.each(mydata, function() {
var template = '<div class="container">';
template += '<div class="name">'+this.name+'</div>';
template += '<div class="address">'+this.address+'</div>';
template += '</div>';
$('body').append(template);
});
EDIT:
If you need your containers numbered with an unique id that's easy too:
var mydata = [{"name": "Tom", "address": "123 Happy Land"},{"name": "Dick", "address": "456 Main Street"},{"name": "Harry", "address": "789 End of the World"}]
$.each(mydata, function(index) {
index=index+1; //so you start at 1 not 0
var template = '<div id="container'+index+'">';
template += '<div class="name">'+this.name+'</div>';
template += '<div class="address">'+this.address+'</div>';
template += '</div>';
$('body').append(template);
});

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