Dynamically adding multiple rows to a datatable - javascript

I see similar questions have been asked before but I cannot find the answer I'm after.
My question is, how do I add multiple rows of data at the same time, I have a working example below which will slowly add 1000 rows using the row.add() but I cannot for the life of me work out how to add these rows in one batch using the rows.add()
$('#addRow').on( 'click', function () {
for (i =0; i < 1000; i++) {
r = [i+'.1', i+'.2', i+'.3', i+'.4', i+'.5', i+'.6', i+'.7'];
mytable.row.add( [ r ] ).draw( false );
}
});
I have gone through all the examples on the web I can find but all of the examples I have found work using a set amount of predefined data, not how to handle an unknown number of rows.
Any help would be greatly appreciated.
Regards, Chris

Without a proper example, I am unable to test the results. Consider the following code.
function addRows(n, tbl) {
var lastRow = tbl.row(":last");
var index = lastRow.index();
for (var i = (index + 1); i < (index + n); i++) {
r = [i + '.1', i + '.2', i + '.3', i + '.4', i + '.5', i + '.6', i + '.7'];
tbl.row.add(r).draw(false);
}
}
$('#addRow').on('click', function() {
addRows(1000, mytable);
});
Assuming you have an amount of data in place, you want to find the last row in the Table and then build on that. You cannot build rows with an infinite number of rows, but you can use a dynamic variable amount. You can also build an Object of Rows and then use table.rows.add().
See More:
https://datatables.net/reference/api/rows()
https://datatables.net/examples/api/add_row.html
https://datatables.net/reference/api/rows.add()

OK I've got it working, so if anyone else gets stuck on this same issue, this is my code now :
$('#addRow').on( 'click', function () {
var arrayAll = [];
for (i =0; i < 1000; i++) {
var arrayRow = [i+'.1', i+'.2', i+'.3', i+'.4', i+'.5', i+'.6', i+'.7'];
arrayAll = arrayAll.concat([arrayRow]);
}
t.rows.add( arrayAll ).draw();
} );
This will add a 1000 rows within a second :)

Related

Javascript, Dynamic Table insert option boxes into table

I have been using excel for my project for a few years. I have finally decided to move it into a html project instead. It kinda sucks as I need to learn everything about JS, CSS and html and probably much more. And my excel project is quite advanced at this point.
But I will just have to start at the beginning and add things as I learn. In the end I think it will be worth it.
So after many hours of trial and error I have been able to create this simple code:
function myFunction2() {
var table = document.getElementById("Table1");
var row = table.insertRow(table.length);
for (i = 0; i < 10; i++) {
row.insertCell(i);
}
row.insertCell(1).innerHTML = "NEW CELL1";
}
And here is the delete function, is that phrased correctly as I thought the numbers where acting strangely
function myDeleteFunction() {
var x = document.getElementById('Table1').rows.length;
var x = (+x - +1);
if (x >= 1) {
document.getElementById("Table1").deleteRow(x);
}
}
This basically insets one new row to my table, However in cells(0,3,4,5,6,7,10) I would need a dropdown list How would I go about to add this ?
Any help would be much appreciated.
In the world of HTML the nearest analogy of a dropdown list is probably select element; a simple example would be (at the end of your myFunction2):
row.insertCell(0).innerHTML = '<select><option>opt A</option><option>opt B</option></select>';
You might want to use the DOM API (to save some parsing & prevent problems from creating HTML directly) - see for example this SO question on how to do so.
Hi guys thanks for your replies. I actually found an answer while waiting , Not sure if my way is the best:
function myFunction2() {
var img = new Image();
var table = document.getElementById("Table1");
var row = table.insertRow(table.length);
for (i = 0; i < 12; i++) {
row.insertCell(i);
}
//Add Txt
row.insertCell(1).innerHTML = "insert";
//Add drop-down list
var dd = document.createElement("select");
dd.name = "SportSelector";
dd.id = "id";
dd.options[dd.length] = new Option("Soccer", "value");
dd.options[dd.length] = new Option("Basket", "value");
dd.options[dd.length] = new Option("Hockey", "value");
row.insertCell(0).appendChild(dd);
//Done
}
I will need to study this. looks like my code was a little long. But of course I solve one problem and I get 10 more :) lol
I'm not sure if it considered polite to ask for a follow up question here as question is solved.
However I feel my next question is closely related to the first one. As my code will add a ton of these drop-downs in the end. I would need somehow to "find" the drop-down again with my next js function.
How would it be possible to add a code that "catches" which drop-down i edit and return a popup msg or something ?
frederik
For adding row you can do something like this
function myFunction2() {
var table = document.getElementById("Table1");
var row = table.insertRow(table.length);
var dropDownHtml = "<select><option>A</option><option>B</option><option>C</option></select>";
var cell;
for (i = 0; i <= 10; i++) {
cell = row.insertCell(i);
if (i == 0 || i == 10 || (i >= 3 && i <= 7)) {
cell.innerHTML = dropDownHtml;
}
}
}
FYI : You can add/remove row at starting my using index 0 and at the end by using index as -1 for insertRow()/deleteRow()
You can modify your delete row function as follows
function myDeleteFunction() {
var x = document.getElementById('Table1').rows.length;
x = (x - 1); //do you want to not allow header to be removed or what ?
if (x >= 1) {
document.getElementById("Table1").deleteRow(x);
}
}

For Loop Manipulate Multidimensional Array Javascript

Okay so I have a 2D array that I am trying to alter using javascript. This is what I have so far:
for (var i = 0; i <= inputData.length; i++ {
inputData[0,0] = inputData[0,0];
inputData[i,0] = inputData[((i - 1) + 1/12), 0];
I want this to take array [i-1] value and then add 1/12 to it
for (j = 13; inputData.length; j += 13) {
delete inputData[j,0];
delete inputData[j,1];
}
Also, I want to delete the entire 2D array at every 13th increment value.
}
This is what I have so far. I am sure there are probably errors within it. Can you guys help me out here? Any help would be greatly appreciated.
Couple of things - you need to be careful when iterating over an array that you're removing from, your indexes will end up offset with respect to your data as soon as you do a delete. Secondly your syntax for deletion is off.
Normally in these situations I favour creating a new array containing the data I want to keep.
var inputData = [[1,1],[2,2],[3,3],[4,4]];
var b = [];
for (i=0; i < inputData.length; i++) {
if ((i + 1) % 13 != 0) {
var year_with_month = inputData[i][0] + i * 1/12;
var e = [year_with_month, inputData[i][1]]
b.push(e);
}
}
inputData = b;
Also, given a choice I'd use a library like underscore to make it easy to do the looping. I never manually write for loops anymore, took me a couple of attempts to get that one right :)

JQuery for loop stuck at last index [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
jQuery Looping and Attaching Click Events
(4 answers)
Closed 9 years ago.
I have function process_row that appends tags to html, and those tags are chained to a function upon clicked. (in this case, simply alert(i), its position in the result array).
But however, upon being clicked, the newly generated alerts the length of the entire result array. I have tried many, many changes to try and make it work, but it doesn't.
Strange thou, fab_div.attr("id", result_data[0]); works fine !! In Chrome inspect element the id tags are displayed as they are, but the click function points everything to the last element in the array.
for example, if I do, fab_div.click(function () { alert(result_data[0]) });, I get the name of the LAST element in the array, doesn't matter which element was clicked.
can anyone please explain to me... WHY??
I think it may have something to do with $("<div>") where JQuery thinks it's the same div that it's assigning to. Is there any way around this? The 's are generated dynamically and I would not want to let PHP do the echoing. Plus the content may be updated realtime.
Example dataset :
Smith_Jones#Smith#Jones#janet_Moore#Janet#Moore#Andrew_Wilson#Andrew#Wilson
After many, many changes, still not working:
function process_row(data){
result_array = data.split("#");
if(result_array.length > 0){
result_data =result_array[0].split("#");
for(i = 0; i < result_array.length; i++){
result_data =result_array[i].split("#");
var fab_text = result_data[1] + " " + result_data[2]
var fab_div = $("<div>");
fab_div.addClass('scroll_tap');
fab_div.attr("id", result_data[0]);
fab_div.append(fab_text)
// fab_div.click(function () { alert(i) });
// ^ not working, try appending list of id's to id_list
id_list.push(result_data[0])
$('#ls_admin').append(fab_div)
}
for(j = 0; j < id_list.length; j++){
$('#' + id_list[j]).click(function () { alert(j) })
}
}
}
Original Attempt:
function process_row(data){
result_array = data.split("#");
if(result_array.length > 0){
result_data =result_array[0].split("#");
for(i = 0; i < result_array.length; i++){
result_data =result_array[i].split("#");
var fab_text = result_data[1] + " " + result_data[2]
var fab_div = $("<div>").append(fab_text).click(function () { alert(i) });
fab_div.addClass('scroll_tap');
fab_div.attr("id", result_data[0]);
$('#ls_admin').append(fab_div)
}
}
}
If you must use an alert, then you can encapsulate the click handler in a self executing function and pass the index to it. Like,
(function (index) {
fab_div.click(function () {
alert(index);
});
})(i);
Although, this is not a clean way to do it. Otherwise, if you are looking to just manipulate the div element is any way, then adding any method directly will also work. Like,
fab_div.click(function () {
alert($(this).attr('id'));
});
You can refer a jsFiddle here
Wonky Solution, but it worked! Haha! Big thanks to Kevin B.
function process_row(data){
result_array = data.split("#");
if(result_array.length > 0){
result_data =result_array[0].split("#");
for(i = 0; i < result_array.length; i++){
result_data =result_array[i].split("#");
var fab_text = result_data[1] + " " + result_data[2]
var fab_div = $("<div>").append(fab_text);
fab_div.addClass('scroll_tap');
fab_div.attr("id", result_data[0]);
$('#ls_admin').append(fab_div)
}
$("#ls_admin").children(this).each(function( index ) {
$(this).append($(this).click(function () { alert($(this).text()) }));
});
}
}

Adding increased count to the DOM for every pass

what I'm hoping to achieve is to increase a count and then append that to the DOM on every pass through using each(). What I have at the moment is the final count added at the end. For example.
Say I have 100 divs, for every pass through it should add the new count as it counts it, like so 1,2,3,4,5,6,7... and so on. But at the moment it counts all the objects and just appends 100 at the end. Please can someone point me in the direction to where I'm going wrong?
I've added a very basic version of what I'm hoping to achieve below... also here is a JSbin (I tried jsfiddle but it seems to be down for me) .
$(".toCount").each(function(i){
$("#count").text(i + 1);
});
$('input').on('click',function () {
var len = $(".toCount").length;
var arr = [];
for (var i = 0; i < len; i++ ) {
arr.push(i+1);
}
$('#count').text(arr.join());
});
I don't know what you mean by 1, 2, 3 ... in case that you want to count the elements step by step you can use setInterval function:
$('input').on('click',function () {
var l = $(".toCount").length,
$c = $('#count'),
i = 0;
var t = setInterval(function() {
i++;
$c.text(i);
if (i === l) clearInterval(t);
}, 10);
});
http://jsbin.com/eronel/17/edit
use append();
Insert content, specified by the parameter, to the end of each element in the set of matched elements.
in your case text() is replacing your div's text so u get 100 at the end ..
$("#count").append(i + 1);
Use append
$("#count").append(i + 1);

How to stop the table from being built again

I've got a lovely table function from josh.trow # link that builds a 4x4 table which can be filled with color. The only problem is is that it rebuilds itself every time I call the function (hence the first time I call the file I see a 4x4 table, the second time I see a 8x4 table, and so on.) It doesn't multiply the rows because they are already limited to 4.
I can't see what check I need to put in that limits the table's columns to only being built once. (4)
Here's the JS code:
function repeatedFunction(L, G, P, D) {
jQuery.fn.reverse = [].reverse;
var completeData = [L, G, P, D];
var max = 4;
$.each(completeData, function(intIndex, objValue) {
if (objValue > max) max = objValue;
});
for (var i = 0; i < max; i++)
{
$('#statSheetTable').append('<tr id="resultRow' + i + '"></tr>');
$.each(completeData, function(intIndex, objValue) {
$('#resultRow' + i).append('<td name="column' + intIndex + '" ></td>');
});
}
$.each(completeData, function(intIndex, objValue) {
$('td[name=column' + intIndex + ']').reverse().each(function(idx, val) {
if (idx < objValue) $(this).addClass('complete' + intIndex);
});
});
}
I tried using a global variable, which stopped the table from being duplicated, but then my color filling code was not functioning (as it can't be refreshed with the new instructions to fill with color).
Essentially what I added to the above function was:
var firstTime = true;
.....
function repeatedFunction(L, G, P, D, 4) {
if(firstTime == true)
{
.....
// code from above block
.....
firstTime = false;
}
Do your experienced JS eyes see where I can limit the table from building more columns?
Here you go chief, updated as you asked.
EDIT: Whoops, now it works :)
http://jsfiddle.net/X83ya/2/
First, always use identical comparison operators when comparing boolean values:
if(firstTime === true)
That being said, you don't need it if you just want to rebuild your table. $('#statSheetTable').append(... will just "add to" whatever was in there. Make sure you clear it out in the beginning like such:
...
var max = 0;
$('#statSheetTable').html('');
...

Categories

Resources