Does anybody know how to convert my data to table by using Javascript or JQuery, I got this data for example:
var data1 = ["1","3","5"]
var data2 = ["a","b","c"]
Once the data1 and data2 value is updated then the rows and columns are also automatic updated.
result:
etc:
No. Alphabet
1 a
3 b
5 c
In your .html file
<table class="myTable"></table>
In your .js file
function generateTable(data1, data2){
var $table = $('.myTable');
for (var i = 0; i < data1.length; i++){
var $aSingleContent = '<tr><td>'+data1[i]+'</td><td>'+data2[i]+'</td></tr>';
$table.append($aSingleContent);
}
}
function modifyData() {
var data1 = ["1","3","5"];
var data2 = ["a","b","c"];
generateTable(data1, data2);
}
--------------------------------Update-------
I put the code in jsfiddle
http://jsfiddle.net/ronansmith/daLf9t85/
remember to add External Resources of jQuery
I like the idea of creating a function to dynamically set the innerHTML of a div, propagating it with a table.
It should look something like this:
function generate_table(array1, array2) {
var html = '<table>';
// cycles through all the elements in the array
for (var i = 0; i < array1.length; i++) {
html += '<tr><td>' + array1[i] + '</td><td>' + array2[i] + '</td></tr>';
}
html += '</table>';
// places the table in the element
document.getElementById('content').innerHTML = html;
}
generate_table() takes in the two arrays and constructs a String, propagating it with the contents of the array in a for loop. Then it gets a div named content and sets its innerHTML to create the table.
In your webpage, be sure to include the div to which the table will be inserted:
<div id="content"></div>
You can also call generate_table() every time your array refreshes, and the table will update.
I hope this helps you!
there are two ways you can do this. one, you wrap a function/class around your data and have a "changedata" method that changes the data and updates the html or you have a setInterval that listens for changes to those variables and serves the changes to you markup. the former is much better than the latter in my opinion
Related
so I wrote a script to display 5 random arrays, but the page doesn't display anything.
here's the code:
<html>
<head>
<script>
function start(){
var arr(5),result;
result=document.getElementById("arraying");
result="<p>";
for(var i=0; i<5;i++){
arr[i]=Math.floor(Math.random()*10);
result+="arr["+i+"]= "+arr[i]+"</p><p>";
}
result+="</p>";
}
window.addEventListener("load",start,false);
</script>
</head>
<body>
<div id="arraying"></div>
</body>
</html>
I tried removing result=document.getElementById and write document.getElementById.innerHTML=result in the end of the function but didn't work. what's the error?
You cannot use the same variable for different purposes at the same time. First you assign a DOM element to result, and immediately on the next line you overwrite result with a string.
Build a string htmlStr inside your loop, and when that is done, assign this string to result.innerHTML property:
function start() {
let arr = [],
result, htmlStr = '';
result = document.getElementById("arraying");
htmlStr += "<p>";
for (let i = 0; i < 5; i++) {
arr[i] = Math.floor(Math.random() * 10);
htmlStr += "arr[" + i + "]= " + arr[i] + "</p><p>";
}
htmlStr += "</p>";
result.innerHTML = htmlStr;
}
window.addEventListener("load", start, false);
<div id="arraying"></div>
Looking at the code you seem to be missing some basic javascript concepts.
array size
This is probably your main issue:
var arr(5)
This does not make sense in javascript. Array length does not need to be predefined since all arrays are of dynamic length. Simply define an array like this:
var arr = []
Then later when you want to append new elements use push like this:
arr.push( Math.floor(Math.random()*10) )
adding html using innerHTML
There are different ways to dynamically inject html into your page. (It looks like) you tried to append the html as a string to the parent element. This is not possible.
You said you tried using innerHTML. That should work if used correctly.
A working implementation would work like this:
function start() {
var arr = []
var result = "<p>"
for(var i = 0; i < 5; i++) {
arr.push( Math.floor(Math.random()*10) ) // Btw this array isn't actually needed.
result += "arr[" + i + "] = " + arr[i] + "</p><p>"
}
document.getElementById("arraying").innerHTML = result
}
window.addEventListener("load", start, {passive: true});
adding html using createElement
A generally better way of dynamically adding html elements is via createElement.
This way you dont have to write html and are therefore less prone for making errors. It is also more performant and easier to integrate into javascript.
I think the best explaination is a commented implementation:
function start() {
var myDiv = document.getElementById("arraying") // get parent node
var arr = []
for(var i = 0; i < 5; i++) {
arr.push( Math.floor(Math.random()*10) )
var p = document.createElement("p") // create p element
p.innerText = "arr[" + i + "] = " + arr[i] // add text content to p element
myDiv.append(p) // append p element to parent element
}
}
window.addEventListener("load", start, {passive: true});
small tips
The let keyword works mostly the same as the var keyword, but is generally preferred because of some edge cases in which let is superior.
Fusing strings and variables using the plus operator is generally considered bad practice. A better way to do the string concatenation would have been
result += `arr[${i}] = ${arr[i]}</p><p>`
I've been struggling with converting the following C# code into something I can use in JavaScript:
var g = Model.List.GroupBy(r => Model.List.IndexOf(r) / 3).ToList();
It's use was to create the appropriate number of rows, with the appropriate number of columns within them. So for example if the list had 6 elements it would allow me to create 3 rows with 2 columns in it, this was all done in razor pages using the above GroupBy and the below code:
foreach (var parent in g)
{
#Html.Raw("<div class='row'>");
foreach (var item in parent)
{
// populate contents of row
}
#Html.Raw("</div>");
}
However for certain reasons I can't do this in Razor and need to create an alternative in JavaScript but I'm struggling to figure out a way to do this.
Primarily because I don't understand entirely how 'GroupBy' creates the list of groups and what would be a suitable alternative.
Any help, or pointing in the right direction would be great. I've tried a few solutions I found online for creating 'GroupBys' but I couldn't get them to work the way I was expecting. I also thought maybe I could split the original list into a list of dictionaries, but again had little success. I'm possibly missing something obvious.
In the end it turns out I was just missing the obvious answer, I found this excellent SO answer. I had looked at slice but couldn't quite visualise how to use it for my problem (obviously been a long day).
The post showed this snippet:
var i,j,temparray,chunk = 10;
for (i=0,j=array.length; i<j; i+=chunk) {
temparray = array.slice(i,i+chunk);
// do whatever
}
In the end my JavaScript code looked something like this:
var listdata = await octokit.repos.listForUser({ "username": "", "type": "owner" });
var chunk = 2;
var loop = 0;
var tempArray = [];
for (var s = 0; s < listdata.data.length; s += chunk) {
tempArray[loop] = listdata.data.slice(s, s + chunk);
loop++;
}
var htmlString = "";
for (var t = 0; t < tempArray.length; t++) {
htmlString += "<div class='row'>";
var innerArray = tempArray[t];
for (var r = 0; r < innerArray.length; r++) {
var repo = innerArray[r];
htmlString +=
"<div class=\"col-md-6 col-sm-6 col-xs-12\">" +
"<div>" + repocontent + "</div>" +
"</div>"
}
htmlString += "</div>";
}
So with a list that's 6 items long, it gets split into an array that contains 3 lists of 2 items. Then I just create the html string using two for loops to create the outer bootstrap rows and the inner column classes. There's probably a more efficient way to do this but this worked a treat.
Which way will be faster and use less memory?
For now i have rendered dynamic <table> by jQuery. Sometimes it has around few thousand cells and it is working so slowly when i do events on it. Html2Canvas is taking alot time to render this table as image. So i wonder about use interactive canvas.
Here is fiddle with script for generating table http://fiddle.jshell.net/j6G66/
I created two examples,
One that mirrors the way you're creating your table
and that's by creating and appending jQuery object elements on every loop iteration:
function createDynamicTable(rows, cols) {
var table = $('<table />');
for(var i=0; i<rows; i++){ // noprotect
var row = $('<tr />');
for(var j=0; j<cols; j++){
var cell = $('<td />');
cell.text("R"+i+"-C"+j);
cell.appendTo( row ); // Appends here....
}
row.appendTo( table ); // Appends here....
}
$('#tableContainer').append( table ); // Appends here....
}
The second one uses a different way of creating a table, that is based instead on the principle of
concatenating a HTML String representation of the needed elements:
function createDynamicTable(rows, cols) {
var table = "<table>";
for(var i=0; i<rows; i++){
var row = "<tr>";
for(var j=0; j<cols; j++){
var cell = "<td>R"+i+"-C"+j+"</td>";
row += cell;
}
row += "</tr>";
table += row;
}
table += "</table>"
$('#tableContainer').append( table ); // Append only once!
}
Now let's be humans and exaggerate a bit creating a table with 1000 rows and 10 cells in each running:
var start = new Date().getTime();
createDynamicTable(1000, 10);
var total = new Date().getTime() - start;
And let's see the results:
IN-LOOP jQuery OBJECTS/EL. CREATION vs. IN-LOOP STRING CONCATENATION
~920 ms ~130 ms
jsBin demo 1 jsBin demo 2
A (logical) side-note on the string concatenation:
you'll not be able to keep copies of alive Objects inside data-* attributes like i.e:
cell = "<td data-objectcopy='"+ myObject +"'>...</td>"
cause the object will result in String "[object Object]", in contrast to jQuery's .data():
cell = $("<td />", {html:"..."}).data("objectcopy", myObject );
where any further change to the object like: $(td).eq(0).data().objectcopy.someProperty = "new value"; will keep it's reference to the original myObject object alive.
this is my code :
html = "";
for (i = 0; i < id_array.length; i++){
html = html.concat($(id_array[i]).clone(true));
}
console.log(html);
The id_array contains 3 ids of the <tr> tag . Instead of the html code from the ids , the result of the html variable is object object object ... Why ? How do I get the html code from this id ?
This is my html code , it is not written by me , it is generated by JQgrid plugin. so i took a picture:
It looks like your want to call outerHTML. In order to do it, you need the native DOM element, you can get it using [0] or get(0) :
var html = "";
for (i = 0; i < id_array.length; i++){
html += $(id_array[i])[0].outerHTML;
}
console.log(html);
clone returns jQuery objects. You don't want to concat them with an empty string. Instead, use an array to store them:
trs = [];
for (i = 0; i < id_array.length; i++){
trs.push($(id_array[i]).clone(true));
}
console.log(trs);
You don't want to use HTML strings when dealing with the DOM.
It seems you may want the outer HTML of the TR elements. Some browsers support it, but not all (and surprisingly not jQuery). In this case you can do something like:
var id_array = ['tr0','tr1','tr2'];
var html = "";
var tbody = $('<tbody>');
for (i = 0; i < id_array.length; i++) {
tbody.append($('#' + id_array[i]).clone(true));
html += tbody.html();
tbody.html('');
}
So I want the array that I get back when I input a manufacturer to show the complete data from each object inside the array in the HTML. However when I call the function in the HTML page I only get back the word object however many times the Manufacturer is defined in the original array. Could anyone help please?
// To make program read the data inside the array cars and pick the ones with the desired manufacturer//
function findManufacturer(manufacturer) {
var retcars = [];
for (i = 0; i < cars.length-1; i++) {
car = cars[i]
if (car.manufacturer == manufacturer) {
retcars.push(car)
}
}
display(retcars);
}
function display(mycars) {
document.getElementById('mycars').textContent= mycars;
}
At the simplest level, you could just use JSON.stringify. That's mostly useful for debugging, though:
function display(mycars) {
document.getElementById('mycars').textContent= JSON.stringify(mycars);
}
You could also iterate through the array, and then through the properties of each car, generating some dynamic HTML:
function display(mycars) {
var html = '';
for (var car in mycars) {
for (var prop in car) {
html += prop + ': ' + car[prop];
}
html += '<hr/>';
}
document.getElementById('mycars').innerHTML = html;
}
Ideally though, you would want to be able to write an HTML template to display the data. I recommend taking a look at some client-side templating engines like Mustache.js or Underscore.js. These engines allow you to write an HTML template with tokens to represent the data fields:
<script type="text/template" id="car-template">
<% _.each(cars, function(car) { %>
<div>
<div><%= make %></div>
<div><%= model %></div>
<div>
<hr/>
<% } %>
</script>
Then you simply write something like this:
function display(mycars) {
var template = _.template(document.getElementById("car-template"));
var html = template({ cars: mycars });
document.getElementById('mycars').innerHTML = html;
}
mycars is an array, so you can't set the text content of an element to be the array...that's why you're getting the famous [Object object] string.
You need to parse the array and turn it into some sort of HTML before inserting it into the DOM.
Try something like this, where we put the contents of mycars into a table and then put it into your <div id="mycars">:
function display(mycars) {
var table = '<table>';
for (var i = 0; i < mycars.length; i++) {
table += '<tr>';
foreach (var prop in mycars[i]) {
table += '<td>' + mycars[i][prop] + '</td>';
}
table += '</tr>';
}
table += '</table>';
document.getElementById('mycars').innerHTML = table;
}
Try those changes:
function display(mycars) {
document.getElementById('mycars').innerHTML= mycars.toString();
}
Advanced use of JSON.stringify
var x={a:"hello",b:[1,2,3]},
y=function(a,b){return typeof b==='string'?undefined:b},
D=document;
D.body.appendChild(D.createElement('pre')).textContent=JSON.stringify(x,y,' ');
Description
JSON.stringify(Array,ReplacerFunction,SpaceToUse)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
The replace function allows you to replace some values inside the array/object before creating the text string. In my case i exclude strings.
Element pre
Also i like to use pre as it's preformatted, so '\n' is a new line '\t' is a tab, in my example i have a simple white space.
Demo
http://jsfiddle.net/T8u32/
with replacer function
http://jsfiddle.net/T8u32/1/