Submit multiple rows jquery datatables - javascript

Im trying to do something similar to this answer: How to add multiple rows to a jQuery DataTable from a html string
The only difference is:
I need to add multiple values that i will get from a text area. The first part works perfectly.
function Gen(){
var data = require('../../cases/config.json');
var tableHeaders;
var cantidad = 0;
$.each(data.Ge[0].Data, function(i, val){
cantidad += 1
tableHeaders += "<th>" + val + "</th>";
});
// Header
$("#tabGen").empty();
$("#tabGen").append('<thead><tr>' + tableHeaders + '</tr></thead>');
var t = $('#tabGen').DataTable({
"scrollY": 200,
"scrollX": true,
rowReorder: true,
autoFill: true,
select:true,
stateSave: true
});
This second part when doing the t.row.add($(info)).draw(); it doesn't appear all the data that i need to show. So when I check out the other answer I saw that I can add a single row from an html string. So I don't know how can I add multiple values inside of the table.
$('#excel').on( 'click', function () {
var inf = $('textarea[name=excel_data]').val();
var rows = inf.split("\n");
for(var y = 0; y < rows.length; y++) {
var cells = rows[y].split("\t");
for(var x in cells) {
var info = '<td><input type="text" id="inputTextAg'+x+'" name="inputTextAg'+x+'" value="'+cells[x]+'" draggable="true" "></td>'
t.rows.add($(info)).draw();
}
}
});
}
Thanks!

Try this:
$('#excel').on( 'click', function () {
var inf = $('textarea[name=excel_data]').val();
var rows = inf.split("\n");
for(var y = 0; y < rows.length; y++) {
var cells = rows[y].split("\t");
var info = '<tr>';
for(var x in cells) {
info += '<td><input type="text" id="inputTextAg'+x+'" name="inputTextAg'+x+'" value="'+cells[x]+'" draggable="true" "></td>';
}
info += '</tr>';
t.rows.add($(info)).draw();
}
});
}

Related

Populate html table with javascript array

I would like to fill an HTML table with a JavaScript array.
But, it doesn't work and I don't know why, my "innerHTML" is not interpreted.
My variable contains the good value, but when I do this :
document.getElementById("title").innerHTML = title;
It doesn't work.
This is my code:
var title = "";
var link = "";
var date = "";
var image = "";
function get_posts() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "my_url");
xhr.onload = function () {
if (xhr.responseText == 0) {
alert("Vous n'avez poster aucun post");
} else {
var posts_array = JSON.parse(xhr.responseText);
for (var i = 0; i < posts_array.length; i++)
{
title = posts_array[i][0];
link = posts_array[i][1];
date = posts_array[i][2];
image = posts_array[i][3];
}
document.getElementById("title").innerHTML = title;
}
}
xhr.send();
}
This is my HTML :
<table id="posts">
<tr>
<th id="test">Titre</th>
<th>Lien</th>
<th>Date</th>
<th>Image</th>
</tr>
<tr>
<td id="title"></td>
<td id="link"></td>
<td id="date"></td>
<td id="image"></td>
</tr>
</table>
You're assigning the value of title inside your loop and then setting the innerHTML of an individual cell to title. Assuming your responseText is formatted correctly, the posts table will only ever contain the last element in your array. It seems like you need to create a new table row for each item in posts_array and add it to the posts table to get your intended result.
e.g.
var t = "";
for (var i = 0; i < posts_array.length; i++){
var tr = "<tr>";
tr += "<td>"+posts_array[i][0]+"</td>";
tr += "<td>"+posts_array[i][1]+"</td>";
tr += "<td>"+posts_array[i][2]+"</td>";
tr += "<td>"+posts_array[i][3]+"</td>";
tr += "</tr>";
t += tr;
}
document.getElementById("posts").innerHTML += t;
You have 3 errors in your code.
You overriding title, link, date and image on each iteration.
You setting only title, I think you want to set all data.
(Posible error) You setting only 1 post into table, probably you
want to see them all.
Easiest (and most common) way to create table from array is build HTML string (with table markup), and append it to table. Unfortunately IE do not support appending html into table, to solve this you may use jquery (it will create Elements from html and append them).
Example:
var posts_array = JSON.parse(xhr.responseText);
var columns = ['title', 'link', 'date', 'image']
var table_html = '';
for (var i = 0; i < posts_array.length; i++)
{
//create html table row
table_html += '<tr>';
for( var j = 0; j < columns.length; j++ ){
//create html table cell, add class to cells to identify columns
table_html += '<td class="' +columns[j]+ '" >' + posts_array[i][j] + '</td>'
}
table_html += '</tr>'
}
$( "#posts" ).append( table_html );
Another way is to use table dom api, this will not require jQuery:
var posts_array = JSON.parse(xhr.responseText);
var columns = ['title', 'link', 'date', 'image']
var table = document.getElementById('posts');
for (var i = 0; i < posts_array.length; i++)
{
var row = table.insertRow( -1 ); // -1 is insert as last
for( var j = 0; j < columns.length; j++ ){
var cell = row.insertCell( - 1 ); // -1 is insert as last
cell.className = columns[j]; //
cell.innerHTML = posts_array[i][j]
}
}
It doesn't work for me.
I want to display wordpress posts into an HTML table.
My JS :
function get_posts() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "myUrl");
xhr.onload = function () {
if (xhr.responseText == 0) {
alert("Vous n'avez poster aucun post");
} else {
var posts_array = JSON.parse(xhr.responseText);
var columns = ['title', 'link', 'date', 'image']
var table_html = '';
for (var i = 0; i < posts_array.length; i++)
{
//create html table row
table_html += '<tr>';
for (var j = 0; j < columns.length; j++) {
//create html table cell, add class to cells to identify columns
table_html += '<td class="' + columns[j] + '" >' + posts_array[i][j] + '</td>'
}
table_html += '</tr>'
}
}
$("#posts").append(table_html);
}
xhr.send();
}
My HTML :
<table id="posts">
<tr>
<th id="test">Titre</th>
<th>Lien</th>
<th>Date</th>
<th>Image</th>
</tr>
</table>
My Web service (i'm using wordpress) :
global $current_user;
if(is_user_logged_in){
$current_user = wp_get_current_user();
}
$array = array();
$posts_array = array('author' => $current_user->ID, "post_type" => "alertes", "orderby" => "date", "order" => "DESC", "post_status" => "publish", "posts_per_page" => "10");
$posts = new WP_Query($posts_array);
if($posts->have_posts()){
while($posts->have_posts()){
$posts->the_post();
$post_array = array(get_the_title(), get_the_permalink(), get_the_date(), wp_get_attachment_url(get_post_thumbnail_id()));
array_push($array, $post_array);
}
echo json_encode($array);
}
else {
echo '0';
}

How to get th when child td is clicked?

I trying to get the <th> content of the clicked <td> item.
here is the fiddle: http://jsfiddle.net/zrccq447/
the thing is, the <th> can have colspan 2 or 3, this is the point where I am stuck. this is my code
$('#table9').on('click', 'td:not(:nth-child(1))', function () {
var td = $(this);
var clicked_pos = td.index();
var x = $('#headerx9 th:nth-child(' + (clicked_pos) + ')').text();
var xy = td.text();
alert(x);
});
i want x to be the <th> of clicked td. the problem is now that if you click on some td that shares the th with other tds, i am getting the wrong th.
appreciate any help
I've updated your JsFiddle with the answer found here: Finding a colSpan Header for one of the cells or td's is Spans
JsFiddle: http://jsfiddle.net/zrccq447/4/
$('#table9').on('click', 'td:not(:nth-child(1))', function () {
var td = $(this);
var clicked_pos = td.index();
var x = $('#headerx9 th:nth-child(' + thLocator[clicked_pos] + ')').text();
var xy = td.text();
alert(x);
});
var thLocator = [], colCount = 1;
$('#table9').find('tr:first th').each(function () {
for (var i = 0; i < this.colSpan; i++) {
thLocator.push(colCount);
}
colCount++;
});
Following on from my comment you need to sum up the colspans (or default 1) for each TH until you get enough to match the column you desire:
http://jsfiddle.net/TrueBlueAussie/zrccq447/5/
$('#table9').on('click', 'td:not(:nth-child(1))', function () {
var td = $(this);
var clicked_pos = td.index();
var cols = 0;
var $table = td.closest('table');
var $ths = $table.find('tr th');
for (var i = 1; i < $ths.length; i++) {
var $th = $ths.eq(i);
cols += ~~$th.attr('colspan') || 1;
if (cols >= clicked_pos) {
var x = $th.text();
alert(x);
break;
}
}
});
I tried to keep it generic, so it finds the appropriate table and headers on the fly.
One approach is to get store a reference to each TH, in order, in an array and call the text from the array based on the location of the td.
var thholder = $('table th'),
th = [];
for(var i = 0; i < thholder.length; i++) {
var thi = $(thholder[i]);
for(var j = 0; j < (thi.attr('colspan') || 1); j++) {
th.push(thi);
}
}
$('#table9').on('click', 'td:not(:nth-child(1))', function () {
var td = $(this);
var clicked_pos = td.index();
alert(th[clicked_pos].text());
});
http://jsfiddle.net/zrccq447/3/
This code is not optimised, but shows the approach:
Loop through all the TH in the table.
If the TH does not have the attribute 'colspan', then set the attribute to a value of 1.
Create a loop for each value of colspan and save a reference to the current TH in the array.
When you click on a TD, get it's clicked position and retrieve the text of the TH at that position in the array and alert it :)

format text fields created

I'm really new so I'll appreciate some help here. please refer to this fiddle.
$(function () {
var input = $('<input type="text" />');
$('#qty').bind('blur', function () {
var n = this.value || 0;
if (n + 1) {
setFields(n);
}
});
function setFields(n) {
$('#newFields').html("");
$('#newFields').append("<table>");
//to create rows and columns
for (i = 0; i < n; i++) {
for (j = 0; j < 1; j++) {
var somestr = "Sample ";
var num = i + 1;
$('#newFields').append("<td>" + somestr + num + ":" + "</td>");
$('#newFields').append("<td>");
var newInput = input.clone();
var newFields1 = $('');
newFields1 = newFields1.add(newInput);
newInput.appendTo('#newFields');
$('#newFields').after("</td>");
}
$('#newFields').after("</tr>");
}
}
});
I'll like to have the input text field appear on the right column (so it should be [column 1]"Sample #" [column 2] input text field, with "Sample 2" and another text field appearing on the next row and so forth). Been trying but couldn't get it. Thanks!
Try appending new rows to the existing table by targeting the table itself on the appendTo() method. You don't need to add a new table and, as you haven't been closing the table off with </table> this isn't working at present anyway.

How to populate a table with vertical and horizontal results?

HeaderA HeaderB HeaderA HeaderB
stuff 232 hey 3434
world 033 boy 221
bat 435 girl 930
This table is dynamic and gets populated live. Here's my JS code, but the logic is not working correctly. I need to tell it that every 2 columns is a new record, and make a new row every 4th column. Here's what I have so far:
function html_data(data) {
var html = '';
$.each(data, function (index, value) {
if ((index+1) % 4 == 0 && index != 0) {
html += '<td>'+value+'</td>';
html += '</tr>'
} else if ((index+1) % 5 == 0) {
html += '<tr>';
html += '<td>'+value+'</td>';
} else {
html += '<td>'+value+'</td>';
}
html += '</tr>';
});
return html;
}
Obviously the above code is completely wrong, but that's all I have so far. If I can the get the mod logic, I can fill in the blanks.
Try this http://jsfiddle.net/G3JK5/
HTML
<table id="table">
<tr>
<th>HeaderA</th>
<th>HeaderB</th>
<th>HeaderA</th>
<th>HeaderB</th>
<th>HeaderA</th>
<th>HeaderB</th>
</tr>
</table>
<input type="button" id="btn" value="Add some random data" />
Javascript
//Sample usage
var tbl = new weirdTable('table');
document.getElementById('btn').addEventListener('click', function(){
tbl.addData([
parseInt(Math.random() * 100),
parseInt(Math.random() * 100)
]);
});
weirdTable
function weirdTable(tableId){
var _me = null;
var _currentIndex = 0;
var _colCount = 0;
var _lastRowIndex = 0;
var construct = function(tableId){
_me = document.getElementById(tableId);
_colCount = _me.rows[0].cells.length;
_currentIndex = _colCount;
};
this.addData = function(data){
var row = _me.rows[_lastRowIndex];
//or var data = arguments;
for(var i = 0; i < data.length; i++){
if(_currentIndex >= _colCount){
_lastRowIndex++;
_currentIndex = 0;
row = _me.insertRow(_lastRowIndex);
}
row.insertCell(_currentIndex).innerText = data[i];
_currentIndex++;
}
};
construct(tableId);
}
Unless I'm missing something, you can just do this:
if (index%4===0) { // start of a row
html += '<tr>';
}
html += '<td>'+value+'</td>';
if (index%4===3) { // end of row
html += '</tr>';
}

Separate rows and columns while creating 2d dynamic table

I can't separate row and column td's as I create a 2d table with jquery..
How do I create 10 rows 10 columns 2d table:
what I have done so far:
$(document).ready(function () {
for (var i = 1; i <= 10; i++) {
$('.box').append('<td/>' + '</p>');
for (var j = 1; j <= 10; j++); {
$('.box').append('<td/>');
}
}
});
http://jsfiddle.net/VS37n/
thnx in advance!
You want a table that has 10 columns and 10 rows.
var rows = 10;
var cols = 10;
In an HTML table structure, rows come first in the hierarchy, so, create those first:
$(document).ready(function() {
var rows = 10;
var cols = 10;
var box = $('.box');
for (var r = 0; r < rows; r++) {
var tr = $('<tr>');
//Here we will append the columns to the row before appending it to the box.
box.append(tr);
}
});
The above code only makes 10 rows for us. Now we need to add 10 columns to each row:
$(document).ready(function() {
var rows = 10;
var cols = 10;
var box = $('.box');
for (var r = 0; r < rows; r++) {
var tr = $('<tr>');
for (var c = 0; c < cols; c++) {
tr.append($('<td><p></p></td>')); //Create the table cell, with a p element as in your example, and append it to the row.
}
box.append(tr);
}
});
See this FIDDLE
UPDATE
I just noticed that the jQuery selector from your post selects the <div> element with class .box. You want to add these rows and columns, however, to a <table> element, which doesn't exist. I'd suggest you add a <table> element into your HTML, or, add it with Javascript before adding the rows.
If you can add a <table> element inside of your .box div, then you would just change the following line:
var box = $('.box');
to:
var box = $('.box table:first');
If you can't change the HTML for some reason, then you can dynamically create the table before the rows and columns:
var box = $('<table>').appendTo('.box');
Is this what you're trying to do?
$(document).ready(function () {
var tdHtml = "":
var trHtml = "";
var tableHtml = "";
for(var i=1;i<=10;i++)
{
tdHtml += "<td></td>";
}
for(var j=1;j<=10;j++);
{
trHtml += ("<tr>" + tdHtml + "</tr>");
}
tableHtml = ("<table>" + trHtml + "</table>");
$('.box').innerHtml(tableHtml);
});
You had a ; after your for loop :
for (var j = 1; j <= 10; j++); {
$('.box').append('<td/>');
}
Furthermore, you are not adding <tr> elements.
See the updated fiddle

Categories