Jquery Mobile Table Reflow - javascript

I'm trying to create my own script for a mobile version of my tables on my website.
Im currently using the script below to get the size of the table, and create new tables for each row, duplicating the headers into each new table.... (see: http://api.jquerymobile.com/table-reflow/ ) to get an idea of what I'm trying to achieve.
My script is as follows, but their is a js fiddle included at the bottom for a better example.
My problem is that I am only able to create 1 inside each table, where it should really be 3 rows, inside of each table. Again check the fiddle below for a proper example. Can anyone see why it is only creating 1 row in the table?
<script>
$(document).ready(function(){
var TableSize = $("table thead tr th").not("table.mobile_table thead tr th").size(); // Get # of columns
var i = 1;
var TableRowCount = $("table tbody tr").size(); // Get # of body rows
$("table thead tr th").each(function(){
$(this).attr("id", i++); // Give headers incrementing ID
});
for ( var CreateTables = 1; CreateTables < TableRowCount; CreateTables++ ){ // Create new table class="mobile_table" for each row
$("table").after("<table class='mobile_table'></table>");
}
$("table.mobile_table").each(function(){// Insert original headers into each row of new table as first column
var h = 1;
while ( ++h < TableSize){ // this is where the error is, it gives me the stuff below but x3 (the number of created tables)......
$("table.mobile_table").after("<tr><td></td><td></td><td></td></tr>");
}
});
console.log(TableSize);
console.log(TableRowCount);
});
</script>
See the fiddle: http://jsfiddle.net/Yf7KV/

Do you mean like this: http://jsfiddle.net/Yf7KV/2/
JS
$(this).append("<tr><td class='mobile_col_1'>Col 1</td><td class='mobile_col_2'>Col 2</td></tr>");
Explanation: Append will alllow you to append elements one after the another. html replaces with what you currently have

Related

Tampermonkey, Chrome how to automatically insert rows into a table?

I've tried with a stupid way of inserting code for a new table, but not even that seems to work. What would be the proper way?
Here's what I tried to do:
var table = document.getElementsByClassName("test")
[0].getElementsByClassName("tableclass");
for (var i = 0, l = table.length; i < l; i++) {
var content = table[i];
let s = content.innerHTML;
s = s.replace(/table/g, 'table border="1"');
s = s.replace(/tr>[\s\S]*?<tr>[\s\S]*?<td>3/g, 'tr>\r\n<tr>\r\n<td>3');
content.innerHTML = s;
}
And a fiddle: https://jsfiddle.net/d10tk7nr/1/
Also, the reason my stupid way doesn't contain the whole table is because some of the cells where I want to eventually use this would contain random data and I don't know how to skip that.
If you want to create a new HTML-Element, every browser got you covered on that.
var tr = document.createElement('tr');
console.log(tr);
The browser console will show you exactly what you have created - a new HTML element that is not yet part of the DOM:
<tr></tr>
The same goes with the creation of some content for that table row:
var td1 = document.createElement('td'),
td2 = document.createElement('td');
td1.innerText = '5';
td2.innerText = '6';
console.log(td1, td2);
The result will be two td-elements:
<td>5</td> <td>6</td>
Now we have to glue these parts together. Browsers will also have you coverd on this:
tr.append(td1);
tr.append(td2);
console.log(tr);
The result is a complete table row:
<tr><td>5</td><td>6</td></tr>
All we have to do is append this row to your table:
var table = document.querySelector('.test table tbody');
table.append(tr);
The elements you have created are now part of the DOM - child elements of the body of your table to be excact.
Click here for a fiddle
Edit
If you want to insert the new row to a specific place, you have to find the element you that should be next to it and use insertBefore. This would change the the last piece of code to:
var targetTr = document.querySelector('.test table tr:nth-child(2)');
targetTr.parentNode.insertBefore(tr, targetTr);
If you want to choose where to put your new row within your javascript, you can use the childNodes property:
console.log(table.childNodes);
I'd use insertAdjacentHTML, like so:
table[i].insertAdjacentHTML('beforeend', '<tr><td>5</td><td>6</td></tr>');
Please see this fiddle: https://jsfiddle.net/52axLsfn/4/
Also demonstrates how to set the border. Note that this code targets all tables, so depending on your situation you may want to be more specific.

Convert HTML table data to JSON using javascript/jquery

My table rows are being dynamically generated when I click "+" button. When I populate the fields and click submit button (next to "+") my JSON gets displayed to the console as shown in the image below.
When I generate JSON, I want to exclude the row which is unfilled (In this case 3rd row). Also, I want exclude column 1 (which consists of 3 buttons).
As we can see the JSON data is consisting lots of "\n" and \t" which is annoying.
I wrote following code by referring to some of the Stack Overflow pages.
function createJSON(){
var myJSON = { Key: [] };
var headers = $('table th');
$('table tbody tr').each(function(i, tr){
var obj = {},
$tds = $(tr).find('td');
headers.each(function(index, headers){
obj[$(headers).text()] = $tds.eq(index).text();
});
myJSON.Key.push(obj);
});
console.log(JSON.stringify(myJSON));
}
The rows that aren't filled have <input> elements. You can use a selector that excludes them.
$('table tbody tr:not(:has(input))').each(...)
You can get rid of all the newline and other whitespace characters around the headings with .trim():
headers.each(function(index, headers){
obj[$(headers).text().trim()] = $tds.eq(index).text();
});
To skip the first column, you can use :gt(0) in the selectors:
var headers = $('table th:gt(0)');
var $tds = $(tr).find('td:gt(0)');

Jquery contenteditable for all cells not rows

I create a table by adding rows and columns with JS and Jquery.
This is my code:
function AddColumnToDataTable(){
$('#tableHeader').append("<th> Header </th>").attr("contenteditable", true);
// Add a new ColumnHeader and set the property "editable"
}
function AddRowToDataTable(){
var count = $('#tableHeader').find("th").length;
// Get the count of Columns in the table
var newRow = $('#tableBody').append("<tr></tr>");
// Add a new Row
for(var i = 0; i < count ; i++){
newRow.find('tr').last().append("<td> Content </td>").attr("contenteditable", true);
// Fill the cells with a default text and set the property "editable"
}
}
So my question is, how can I write the code, that each cell is editable? At the moment, when I click, the whole row goes editable? Each cell should have that property.
I found a code that could help:
//$('table th:nth-child(4)').attr("contenteditable", true)
This makes the 4th header/cell editable, but how can I use it, each new created header/cell is the nth-child?
The jQuery append function doesn't return the new [appended] element, rather it returns the element that was appended to, hence the error in your code. Regardless, it's easier just to set the attribute manually in the append string. So, change this line:
newRow.find('tr').last().append("<td> Content </td>").attr("contenteditable", true);
To this:
newRow.find('tr').last().append("<td contenteditable="true"> Content </td>")
That should do it
It worked with
$('table td').last().attr("contenteditable", true);

changing the values of height attribute of table cells using jquery or javascript

I have two tables say table 1 and table 2.(both having equal number of rows)
For each of the rows in table 1, I wish to set the height of the corresponding cells in table 2 equal to the corresponding cell in table 1. i.e table2-row1-col1 = table1-row1-col1 and similar.
Please help me .
Use .each to loop through the rows in the first table, and use .eq() to select the table-2 row which corresponds to each table-1 row:
$('#table1 tr').each(function(i,el) {
var hgt = $(this).height();
$('#table2 tr').eq(i).height(hgt);
});
http://jsfiddle.net/mblase75/sCdRk/
Assuming both tables have the exact same number of rows, the below should work. If they differ you'll need to check the existence of a matching table1 row before setting the height.
var $table1 = $("#table1");
var $table2 = $("#table2");
$("TR", $table2).each(function(index) {
$(this).css("height", $("TR", $table1).eq(index).css("height"));
});
Fiddle here to prove it works.
First, you must make sure the two tables have the same number of rows or add some index check codes to avoid OutOfIndex error.
Here is some codes, just FYI:
var tbl2Rows = $("#tbl2 > tbody > tr");
$("#tbl1 > tbody > tr").each(function(index){
console.log($(this).height());
$(tbl2Rows.get(index)).height($(this).height());
});

Javascript: How can I remove appended child row (tr)?

I am using JS to append array data to a table.
I am trying to add a button that removes the appended data, and puts its own data in instead. I can get the data to be added, but I cant get the data removed.
I have tried these with no luck -
.children().last().remove();
&
.removeChild() ;
I have a fiddle but I cant get the original data remove when new added (button now works! -thanks) - http://jsfiddle.net/2waZ2/37/
What code do I add so when the new line from the array is added the old data is removed?
Code to append on load:
var row = document.createElement('tr');
row.innerHTML = displayArrayAsTable(QR4, 24, 25);
document.getElementById('mytable').appendChild( row ) ;
Button code to add data:
function addNewRow() {
var row = document.createElement('tr');
row.innerHTML = displayArrayAsTable(QR4L, 24, 25);
document.getElementById('mytable').appendChild( row ) ;
}
http://jsfiddle.net/2waZ2/47/
Removing the 1st child row:
var table = document.getElementById('mytable');
table.removeChild(table.children[1])
I have updated the fiddle and it works fine now.
You can use something like this before adding the new row:
var last = document.getElementById('mytable').lastChild ;
document.getElementById('mytable').removeChild(last);
A trivial answer with jQuery: http://jsfiddle.net/guard/2waZ2/48/

Categories

Resources