I was hoping some would know how to tile a grid across. I have some code to get started
1 | 2
3 | 4
5 | 6
and in my ajax function
$.ajax({
complete:function(result) {
// in here i want to tile across two sets of td's for each tr
for(var i = 0; i < products.length; i++) {
$('#products').append('<tr><td>' + products[i].Title + '</td></tr>');
}
}
});
<table id="products"></table>
This works whatever the products size is (even or odd).
Hope with comments make it easy to understand
var table_body = '< tbody>';
for(var i = 0; i < products.length; i++) {
if(i%2==0)//if even we open a row
table_body += '<tr>';
//We always put a value
table_body += '<td>' + products[i].Title + '</td>';
if(i%2!=0 || (i==products.length-1))//if odd we close a row
table_body += '</tr>';
}
table_body += '< /tbody>';
$('#products').append(table_body);
Here is a sample code of what you are trying to achieve. You can optimize it to suit your needs. Fiddle
for(var i = 0, y=0; i < 10; i++){
if(y == 0){
$('table').html($('table').html() + '<tr>');
}
$('table').append('<td>' + i + '</td>')
y++;
if( y == 2 ){
y = 0;
$('table').html($('table').html() + '</tr>');
}
}
The simplest solution is to simply not use a table. Chances are if you're arranging data this way, it's not tabular data anyway. I recommend using display: inline-block on your elements and using an HTML element that makes sense for the data you're using, like a ul or li.
This will work for even or odd numbers of elements, fully tested.
var tbl = "";
for (var i = 0; i < products.length; ++i) {
if (i % 2 == 0) tbl += '<tr>';
tbl += '<td>' + products[i].Title + '</td>';
if (i % 2 == 1) tbl += '</tr>';
}
if (i % 2 == 1) tbl += '</tr>';
$("#products").append(tbl);
fiddle
Related
I'm new to javascript and HTML, and I am looking to dynamicaly create a table with a loop in javascript inside of a HTML file.
I have the code to create a table, but I am struggling to get it to increase by one cell each row.
I feel as though I need to add 1 my cell variable each time the for loop runs, I assume its something like cells++ but when ever I do this the html file wont load anything, any ideas on where to place it within my for loops? or am I totaly on the wrong path?
<script>
var table = "", rows = 1, cells = 1;
for (var r = 0; r < rows; r++) {
table += "<tr>";
for (var c = 1; c <= cells; c++) {
table += "<td>" + c + "</td>"
}
table += "</tr>"
}
document.write("<table border =1>" + table + "</table>")
</script>
This is what I want it to look like:
In order to get "stairs" look-like table, the amounts of rows and cells should be equal. Example below is how to do it properly. In order to change amount of rows, change value of variable from 7 to what you want ;)
var table = "";
rows = 7;
for (var r = 0; r <= rows; r++) {
table += "<tr>";
for (var c = 1; c <= r; c++) {
table += "<td>" + c + "</td>";
}
table += "</tr>";
}
document.write("<table border =1>" + table + "</table>");
I have been able to successfully read in a CSV file from a URL, parse through it, and write it out to a table. Simple to most but a Herculean effort for me. There is a header row, and each row contains 4 values (the first will be disregarded).
What I need to do is to be able to write each row to a different place on my page at will. I assume to do this I'd need to load each row into a slot in an array, where I can then call them specifically. For example if I want the 3rd entry, and also be able to access each value to build my text string, it would have to look something like:
document.getElementById("snow").innerHTML = 'Trail Status: ' + trail[2].status + 'Report Date: ' + trail[2].reportDate;
I know that the above code probably is flawed, but it was more illustrative than anything.
What I don't know how to do is setup an array to hold each row (so they can be accessed individually), define each value so it can be a accessed (trail, reportDate,etc), and read the CSV properly into that array.
I'm currently using jQuery and the code below to read, parse, and create the table.
$.ajax({
url: 'https://data.import.io/extractor/...',
dataType: 'text',
}).done(successFunction);
function successFunction(data) {
var allRows = data.split(/\r?\n|\r/);
var table = '<table>';
for (var singleRow = 0; singleRow < allRows.length; singleRow++) {
if (singleRow === 0) {
table += '<thead>';
table += '<tr>';
} else {
table += '<tr>';
}
var rowCells = allRows[singleRow].split(',');
for (var rowCell = 0; rowCell < rowCells.length; rowCell++) {
if (singleRow === 0) {
table += '<th>';
table += rowCells[rowCell];
table += '</th>';
} else {
table += '<td>';
table += rowCells[rowCell];
table += '</td>';
}
}
if (singleRow === 0) {
table += '</tr>';
table += '</thead>';
table += '<tbody>';
} else {
table += '</tr>';
}
}
table += '</tbody>';
table += '</table>';
$('body').append(table);
}
Any direction to reaching my end state would be greatly appreciated. Ultimately I'm building a dashboard that will show the Trail Conditions (from the CSV) and 10-day weather forecast (from Wunderground) to help plan Snowmobile Trips for local Michigan snowmobilers.
Thanks!
Marc
Create a multidimensional array - with 2 dimensions. The first index will access each row. The second index will access each cell within a row.
This reference may help: https://trans4mind.com/personal_development/JavaScript/Array2D.htm
This is an example using your current for loops.
function successFunction(data) {
var parsedData = [];
var allRows = data.split(/\r?\n|\r/);
for (var singleRow = 0; singleRow < allRows.length; singleRow++) {
var rowCells = allRows[singleRow].split(',');
for (var rowCell = 0; rowCell < rowCells.length; rowCell++) {
parsedData[singleRow][rowCell] = rowCells[rowCell];
}
}
}
Thanks for the input, i found that PapaParse was the way to go! The data was easy to get at and I had no problems!
I a trying to dynamically add rows and populate them with 3 col-sm-4 using a modulo against the number of objects in a returned object from a function.
Code:
function formatSeriesCard(series) {
var card = "";
console.log(countProperties(series));
for (var i=0; i < countProperties(series); i++) {
if (i % 3 == 0 ) {
card += "<div class=\"row\">";
}
card += "<div class='col-sm-4' data-id="+i+">";
card += "<div class='action-box'>";
card += "<h4>" + '"' + series.name + '"' + "</h4>";
card += "<p>";
Instead I'm getting each row nested within the previous. Thinking I need to test for the first one and last one. Thanks.
Here is something like what you want
Bootply : http://www.bootply.com/2xnJBpyVsS
JS :
var wantedcol=14;
var mycol='<div class="col-xs-4">mycol</div>';
var startRowLabel="<div class='row'>";
var endRowLabel="</div>";
var start = "";
var end="";
var toAppend="";
for(var i=0; i<wantedcol; i++){
start="";
if(i%3==0 || i==0){
start=startRowLabel;
}
end="";
if(i!=0 && (i%3==2 || i==wantedcol-1)){
end=endRowLabel;
}
console.log(start+mycol+end);
toAppend+=start+mycol+end;
}
$('.container').append(toAppend);
HTML:
<div class="container"></div>
Comment :
You just have to take care about when you have to insert the div.row opening and closing tags
I am wondering how to create a function with a for loop which creates new cells / rows for the other for loop to call upon. The function should return newRow which should be a specified amount of cells. The idea is the html code displays 3 images per row, but if there is just 2 images then it only needs 2 cells. That is the first if / else statement.
Here is the code so far..
var cells = document.getElementsByTagName('td');
var cell = '<td>' + cells[0].innerHTML + '</td>';
//console.log(cell);
document.getElementById('searchBtn').onclick = search;
//specified as 3 per row
var NUMPERROW = 3;
//gets number from form text input
var num = document.getElementById("searchtxt").value;
function search(){
//var num = 4;
console.log(num);
//loop once per row
var htmlStr = '';
for (var i = 0; i < num; i = i + NUMPERROW){
//htmlStr += '<tr>' + cell + cell + cell + '</tr>;
if (num - i >= NUMPERROW) {
//displays a new row of 3
htmlStr += newRow(NUMPERROW);
}else { //less then 3 to display
htmlStr += newRow(num - i);
}
}
document.getElementById('thumbnails').innerHTML = htmlStr;
}
/*
*Returns the html for a new row.
* numToAdd: the number of cells to add for this row.
*
*/
//this function i do not know how to write
function newRow(cellsToAdd){
/////?????????? should be a for loop return new Row for the for loop above
}
}
Here is a simple function if you don't want to pass the values you can leave content out.
function newRow(numberOfCells, content)
{
var result = '<tr>';
for(var i = 0; i < numberOfCells; i++)
result += '<td>' + content[i] + '</td>';
result += '</tr>';
return result;
}
I'm trying to use javascript with jQuery to convert a tab delimited string to html table.
In the input string rows are separated by <br/> and columns by tabs.
Here's what I have so far:
$(function(){
$('div.jstable').each(function(){
var text = $(this).html();
var rows = text.split(/<br>/i);
var htmlString = "<table class='display dataTable'>"
var startTbody = true;
for(i = 0; i< rows.length; i++){
// build header section
if (i == 0){
htmlString += '<thead>';
}else {
if (startTbody){
htmlString += '<tbody>';
startTbody = false;
}
}
htmlString += '<tr>';
var row = rows[i];
var columns = row.split('\t');
// build columns
for (j = 0; j < columns.length; j++ ){
if (i == 0){
htmlString += '<th>' + columns[j] + '</th>';
}else {
htmlString += '<td>' + columns[j] + '</td>';
}
}
htmlString += '</tr>';
if (i == 0){
htmlString += '</thead>'
} else {
if (i == rows.length - 1){
htmlString += '</tbody>'
}
}
}
htmlString += '</table>';
$(this).html(htmlString);
})
});
And here is the input text:
<div class="jstable" style="float: left">
col1 col2 col3<br />asda fd dfs<br />mmmm ffff ssss
</div>
Unfortunately in IE8/7 the text returned by jquery .html() function has all tabs replaced by spaces.
IE9 is fine, also current versions of Firefox & Chrome work fine.
Any ideas?
You can pass a regular expression to split(). /\s+/ will consider consecutive whitespace of any kind as a single delimiter:
>>> "one two".split(/\s+/)
["one", "two"]
>>> "one\ttwo".split(/\s+/)
["one", "two"]
>>> "one\ntwo".split(/\s+/)
["one", "two"]
FWIW I found out that if I surround the input text with <pre> tags the .html() function will return the text with tabs in IE7/8, as expected.
So, the initial example source html will look like this:
<pre class="jstable" style="float: left">
col1 col2 col3<br />asda fd dfs<br />mmmm ffff ssss
</pre>