Related
this is my json:
{
"box 1": [{
"difficulty_grade": "5a+"
}, {
"gym": "New_gym"
}, {
"route_author": "some author"
},]}
This is my code: variable groups contain json which showed on image
for (var k in groups){
$p("#panel").append('<div class="flip_sector">' + k + '<span style="float:right;margin-right:7px" id="fav_m"><i class="fa fa-plus-circle" aria-hidden="true"></i></span><div class="sect_n"></div></div>');
for (var i = 0; i<groups[k].length;i++){
$p("<span>"+groups[k][i]['route_author']+" | "+groups[k][i]['route_author']+"</span>").insertAfter(".flip_sector");
Variable groups in this json on image.
console.log(groups[k][i]['difficulty_grade']);
}
}
I need to create a slidetoogle with header box 1, box2, ... , and body whick contain data from objects.
This is my output:
In this output show only first object from box 1. Can You help my?
You use second for incorrectly.
for (var k in groups){
for (var i in groups[k]){
console.log(groups[k][i]['difficulty_grade']);
}
}
I fix my problem. This is fixed code.
var count = 0;
for (var k in groups){
$p(".loader_sector").append('<div class="flip_sector" id="sector_id_'+count+'"><div class="header" style="padding: 6px;margin-bottom:4px;margin-left: -10px;padding-left: 13px;">' + k + '<span style="float:right;margin-right:7px" id="fav_m"><i class="fa fa-plus-circle" aria-hidden="true"></i></span></div><div id = "container_id_'+count+'" class="container_class" style="display:none"></div></div>');
console.log(groups[k]);
for (var i = 0; i< groups[k].length; i++) {
console.log(groups[k][i]['difficulty_grade']);
$p("#container_id_"+count+"").append("<div class='pan_sect' data-count='"+count+"'><div style='margin-bottom:-33px'><img style='height:46px!important;border-radius:100%' src='/dev/application/modules/User/externals/images/nophoto_user_thumb_profile.png'/><div style ='position:relative;bottom:46px;left:64px;color:#009c89'>"+ groups[k][i]['route_author'] +"</div>" + "<span style = 'font-size:10px;color:grey;position:relative;left:64px;bottom:46px'>" + groups[k][i]['route_name'] + "| Grade: " + groups[k][i]['difficulty_grade'] + "| Box4" + "</span></div><hr style='width:96%'></div>");
}count++;
}
Problem: When I append here:
$p("#container_id_"+count+"").append("<div class='pan_sect' data-count='"+count+"'><div style='margin-bottom:-33px'><img style='height:46px!important;border-radius:100%' src='/dev/application/modules/User/externals/images/nophoto_user_thumb_profile.png'/><div style ='position:relative;bottom:46px;left:64px;color:#009c89'>"+ groups[k][i]['route_author'] +"</div>" + "<span style = 'font-size:10px;color:grey;position:relative;left:64px;bottom:46px'>" + groups[k][i]['route_name'] + "| Grade: " + groups[k][i]['difficulty_grade'] + "| Box4" + "</span></div><hr style='width:96%'></div>");
earlier I add new div with the same class. I create difficult id's using variable count and add it to $p("#container_id_"+count+"")
I am having trouble saving the new row. When i click on add person I am able to input the data, however, i am not sure how to save it and add a new row.
I know i have to make a function for the save button to work however i am stuck on how to make it work. I have tried a few times but to no avail.
var isNewLineToggled = false;
var isAscending = {
name : false,
lastName: false,
dob: false
};
$(".main").append("<input placeholder='search by name' class='search'/><br/><br/>")
$(".main").append("<button onclick=addPerson()>add a person</button><br/><br/>")
var table = $(".main").append("<table></table>");
var thead = '<thead><tr></tr></thead>';
table.append(thead);
var header = [
{ title: 'Name', sortBy: 'name'},
{ title: 'Last Name', sortBy: 'lastName'},
{ title: 'Date of birth', sortBy: 'dob'}
].map(
function(header) {
var sortButton = '<button id="' + header.sortBy + '" onclick=sortRows("'+ header.sortBy + '")>/\\</button>';
$('thead').append('<th>' + header.title + ' ' + sortButton + '</th>');
}
)
var tbody = "<tbody></tbody>";
var data = [ {name: 'Peter', lastName: 'Petterson', dob: '13/12/1988'},
{name: 'Anna', lastName: 'Jones', dob: '06/02/1968'},
{name: 'John', lastName: 'Milton', dob: '01/06/2000'},
{name: 'James', lastName: 'White', dob: '30/11/1970'},
{name: 'Luke', lastName: 'Brown', dob: '15/08/1999'}
];
$('.search').change(function(event) {
searchedName = event.target.value;
})
table.append(tbody);
data.map(
function(row, i) {
$('tbody').append(
'<tr><td>' + row.name +
'</td><td>' + row.lastName +
'</td><td>' + row.dob +
'</td><td><button onclick=editRow('+i+')>edit</button><button>delete</button></td></tr>'
)
}
)
var editableRow = "<td><input/></td><td><input/></td><td><input type='date'/></td><td><button onclick=saveRow()>save</button></td>";
var addPerson = function() {
isNewLineToggled = !isNewLineToggled;
if (isNewLineToggled) {
$('tbody').prepend('<tr>' + editableRow + '</tr>')
} else {
$('tbody > tr:first-child').remove();
}
}
var editRow = function(rowNumber) {
var name = $('tbody > tr:nth-child('+(rowNumber + 1)+') > td:first-child').text();
var lastName = $('tbody > tr:nth-child('+(rowNumber + 1)+') > td:nth-child(2)').text();
var dob = $('tbody > tr:nth-child('+(rowNumber + 1)+') > td:nth-child(3)').text();
$('tbody > tr:nth-child('+(rowNumber + 1)+')').html(editableRow2);
$('tbody > tr:nth-child('+(rowNumber + 1)+') > td:first-child > input').val(name);
$('tbody > tr:nth-child('+(rowNumber + 1)+') > td:nth-child(2) > input').val(lastName);
}
You can add row like this, two small changes:
$(".main").append("<button class='add'>add a person</button><br/><br/>")
Remove inline event handler, no need for it. And your function could be:
$('body').on('click','.add', function() { //you will need event delegation, because of dynamically added elements
isNewLineToggled = !isNewLineToggled;
if (isNewLineToggled) {
$('tbody').prepend('<tr>' + editableRow + '</tr>')
} else {
$('tbody > tr:first-child').remove();
}
});
Since your editableRow variable isn't defined, i've used just one cell with text for demo:
https://jsfiddle.net/2c97auey/1/
P.S. Your editableRow should have input(s) values, properly placed in cells. Shouldn't be too hard.
Ok so Im building a product sorting watch and this is what I have so far.
jQuery(document).ready(function() {
// starter jQuery file
/* Watches Array */
var watchesArray = [
{
model: "Swim",
image:"",
price: 149.99,
sports:["Swimming"],
touchScreen:false,
GPS:false,
heartRateMonitor:false,
hrZoneTraining:false,
caloriesBurned:true,
distance:true,
pace:true,
multisport:false,
swimMetrics:true,
memory:"Up to 30 workouts",
virtualPartner:false,
virtualRacer:false,
paceAlert:false,
timeDistanceAlert:false,
hydrationAlert:false,
rechargeableBattery:false,
waterResistant:"Up to 50 meters",
syncWithComputer:true,
other:"",
},
{
model: "FR 10",
image:"fr_10.jpg",
price: 129.99,
sports:["Running"],
touchScreen:false,
GPS:true,
heartRateMonitor:false,
hrZoneTraining:false,
caloriesBurned:false,
distance:true,
pace:true,
multisport:false,
swimMetrics:false,
memory:"Up to 7 workouts",
virtualPartner:false,
virtualRacer:false,
paceAlert:false,
timeDistanceAlert:false,
hydrationAlert:false,
rechargeableBattery:true,
waterResistant:"Up to 50 meters",
syncWithComputer:false,
other:"-Virtual Pacer(compares running pace to target)</br>-Walk/Run feature",
checkBox:"<input type='checkbox' name='he' value='jk' id='compare'>"
},
{
model: "FR 15",
image:"fr_15.jpg",
price: 199.99,
sports:["Running"],
touchScreen:false,
GPS:true,
heartRateMonitor:true,
hrZoneTraining:true,
caloriesBurned:true,
distance:true,
pace:true,
multisport:false,
swimMetrics:false,
memory:"Up to 7 workouts",
virtualPartner:false,
virtualRacer:false,
paceAlert:false,
timeDistanceAlert:false,
hydrationAlert:false,
rechargeableBattery:true,
waterResistant:"Up to 50 meters",
syncWithComputer:false,
other:"-Virtual Pacer (compares running pace to target) </br>Walk/Run feature</br>-Activity",
},
{
model: "FR 220",
image:"fr_220.jpg",
price: 299.99,
sports:["Running"],
touchScreen:false,
GPS:true,
heartRateMonitor:true,
hrZoneTraining:true,
caloriesBurned:true,
distance:true,
pace:true,
multisport:false,
swimMetrics:false,
memory:"200 hours of data",
virtualPartner:false,
virtualRacer:false,
paceAlert:true,
timeDistanceAlert:false,
hydrationAlert:true,
rechargeableBattery:true,
waterResistant:"Up to 50 meters",
syncWithComputer:true,
other:"-Walk/Run feature</br>-Interval Training",
},
{
model: "FR 620",
image:"fr_620.jpg",
price: 449.99,
sports:["Running"],
touchScreen:true,
GPS:true,
heartRateMonitor:true,
hrZoneTraining:true,
caloriesBurned:true,
distance:true,
pace:true,
multisport:false,
swimMetrics:false,
memory:"200 hours of data",
virtualPartner:true,
virtualRacer:false,
paceAlert:true,
timeDistanceAlert:true,
hydrationAlert:true,
rechargeableBattery:true,
waterResistant:"Up to 50 meters",
syncWithComputer:true,
other:"-VO2 Max</div></br>-Walk/Run feature</br>-Interval Training",
},
{
model: "FR 310 XT",
image:"",
price: 349.99,
sports:["Multisport"],
touchScreen:false,
GPS:true,
heartRateMonitor:true,
hrZoneTraining:true,
caloriesBurned:true,
distance:true,
pace:true,
multisport:true,
swimMetrics:false,
memory:"1000 laps",
virtualPartner:true,
virtualRacer:true,
paceAlert:true,
timeDistanceAlert:true,
hydrationAlert:true,
rechargeableBattery:true,
waterResistant:"Up to 50 meters",
syncWithComputer:true,
other:"-Interval Training",
},
{
model: "FR70",
image:"",
price: 149.99,
sports:["Fitness"],
touchScreen:false,
GPS:false,
heartRateMonitor:true,
hrZoneTraining:true,
caloriesBurned:true,
distance:true,
pace:true,
multisport:false,
swimMetrics:false,
memory:"Up to 20 hrs of data",
virtualPartner:true,
virtualRacer:false,
paceAlert:true,
timeDistanceAlert:true,
hydrationAlert:false,
rechargeableBattery:false,
waterResistant:"Up to 50 meters",
syncWithComputer:true,
other:"-Interval Training",
},
];
/* End Watch Array */
/* different sports arrays filtered */
var runningArray = watchesArray.filter(function(watch) {
return watch.sports.indexOf('Running') !== -1;
});
var swimmingArray = watchesArray.filter(function(watch) {
return watch.sports.indexOf('Swimming') !== -1;
});
var multisportArray = watchesArray.filter(function(watch) {
return watch.sports.indexOf('Multisport') !== -1;
});
var fitnessArray = watchesArray.filter(function(watch) {
return watch.sports.indexOf('Fitness') !== -1;
});
function compare() {
if ($('#page-2 div:nth-of-type(1)').hasClass('running-category')) {
var sportArray = runningArray;
}
if ($('#page-2 div:nth-of-type(2)').hasClass('swimming-category')) {
var sportArray = swimmingArray;
}
if ($('#page-2 div:nth-of-type(3)').hasClass('multisport-category')) {
var sportArray = multisportArray;
}
if ($('#page-2 div:nth-of-type(4)').hasClass('fitness-category')) {
var sportArray = fitnessArray;
}
var sportArrayLength = $(sportArray).length;
for (var i = 0; i < sportArrayLength; i++) {
var watchModel = "<div class='watch-model'>"+sportArray[i].model+"</div>",
watchImage = "<div class='watch-image'>"+sportArray[i].image+"</div>",
watchPrice = "<div class='watch-price'>$"+sportArray[i].price+"</div>",
watchSports = "<div class='watch-sports'>"+sportArray[i].sports+"</div>",
watchTouch = "<div class='watch-touch'>"+sportArray[i].touchScreen+"</div>",
watchGPS = "<div class='watch-gps'>"+sportArray[i].GPS+"</div>",
watchHeart = "<div class='watch-heart'>"+sportArray[i].heartRateMonitor+"</div>",
watchHRZone = "<div class='watch-zone'>"+sportArray[i].hrZoneTraining+"</div>",
watchCalories = "<div class='watch-calories'>"+sportArray[i].caloriesBurned+"</div>",
watchDistance = "<div class='watch-distance'>"+sportArray[i].distance+"</div>",
watchPace = "<div class='watch-pace'>"+sportArray[i].pace+"</div>",
watchMultiSport = "<div class='watch-swim-metrics'>"+sportArray[i].multisport+"</div>",
watchSwimMetrics = "<div class='watch-multi'>"+sportArray[i].multisport+"</div>",
watchMemory = "<div class='watch-memory'>"+sportArray[i].memory+"</div>",
watchVirtualPartner = "<div class='watch-virtual-partner'>"+sportArray[i].virtualPartner+"</div>",
watchVirtualRacer = "<div class='watch-virtual-racer'>"+sportArray[i].virtualRacer+"</div>",
watchPaceAlert = "<div class='watch-pace-alert'>"+sportArray[i].paceAlert+"</div>",
watchTimeDistanceAlert = "<div class='watch-time-distance-alert'>"+sportArray[i].timeDistanceAlert+"</div>",
watchHydrationAlert = "<div class='watch-hydration'>"+sportArray[i].hydrationAlert+"</div>",
watchRechargeable = "<div class='watch-rechargeable'>"+sportArray[i].rechargeableBattery+"</div>",
watchWaterResistance = "<div class='watch-water-resistance'>"+sportArray[i].waterResistant+"</div>",
watchSync = "<div class='watch-syncs'>"+sportArray[i].syncWithComputer+"</div>",
watchOther = "<div class='watch-other'>"+sportArray[i].other+"</div>",
watchesTotal ="<div class='item-container'>"+ watchModel + watchImage + watchPrice + watchSports + watchTouch + watchGPS + watchHeart + watchHRZone + watchCalories + watchDistance + watchPace + watchMultiSport + watchSwimMetrics + watchMemory + watchVirtualPartner + watchVirtualRacer + watchPaceAlert + watchTimeDistanceAlert + watchHydrationAlert + watchRechargeable + watchWaterResistance + watchSync + watchOther+"</div>"
;
$('.comparison-container').append(watchesTotal);
// alert(watchModel)
}
} //end function
$("#page-4 .continue-button").click(function() {
$('.comparison-container').empty();
compare();
});
//var inArray = $.inArray(true, watchesArray[0].multisport)
// alert(inArray)
}); // ready method
So the flow is basically click a sport, filter through the array and make new array with only those items that have that sport, then select a som features that you which to have and when click continue those items that meet the criteria are displayed.
For the last part which is where I am stuck is that when those watches are displayed I have to be able to select a checkbox of those products that interest me so I can then continue and have those selected watches display with all of their details. So basically I need to figure out how to compare two objects from an array by selecting the ones that I want from the page.
On Page 3 you basically have a list of the array items and a compare checkbox under each one.I just need to be able to pass on those products that were selected to the next page
how to compare two objects from an array
Use JSON.stringify to compare the literals:
var foo = [{"1":2},{"1":3},{"2":3},{"1":2}];
var bar = JSON.stringify(foo[0]) === JSON.stringify(foo[1]);
var baz = JSON.stringify(foo[0]) === JSON.stringify(foo[3]);
Use an array as the second param to guarantee ordering of the key enumeration:
(JSON.stringify({a: 1, b: 2}, ["a","b"]) === JSON.stringify({b: 2, a: 1}, ["a","b"]))
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+)
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);