jQuery Dynamically create div, populate tbody and append to existing div - javascript

Basically I have a <div class='preferences-grid'> which already exists.
On click of button preferences-grid-btn-ok I want to call the function create() which will:
create a new <div class='preferences-container'> and
populate the tbody based on a for.
My problem is that I can't append the rows created by the for to the tbody of the individual <div class='preferences-container'> that are being created each time the button is clicked.
When I'm using this:
jQuery(contents).find(".preferences-table-body").append(row);
no rows are appended and when I'm using
jQuery(".preferences-table-body").append(row);
the first time no rows are appended and after that the new rows are appended to all of the existing <div class='preferences-container'>
here is the jsfiddle link

You were creating a string contents, but jquery had no way of knowing of its existence.
Here's a working fiddle: http://jsfiddle.net/c524Loam/
function create() {
var contents = "..."
var $contents = $(contents);
for (i = 0; i < 3; i++) {
var row = $('<tr></tr>').addClass('bar').text('result ' + i);
$contents.find(".preferences-table-body").append(row);
}
return $contents;
}
I created a new jquery object using contents and then manipulated it in the for loop. After return it gets appended to the markup.

Related

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);

Add class name to appended child elements with jquery

I have a table like this.
<table id='table1'>
</table>
and in this table i am dynamically adding rows to the table using jquery like below.
var tbl = $("#table1");
tbl.append('<tr></tr><tr></tr><tr></tr>');
I can add class to the appended rows using 2 methods like below
case 1
tbl.find('tr').eq(0).addClass("test");
tbl.find('tr').eq(1).addClass("test");
or case 2
for (var i=0;i<tbl.find('tr').length;i++) {
tbl.find('tr').eq(i).addClass("test")
}
and my question is there any way i can add same classname to the dynamically appended rows. Answers expecting in jquery. Thanks in advance.
Once an element is added to the DOM, you have no way of telling if it was dynamically added or not unless you have custom code that does such. I would suggest changing .append to .appendTo so you have access to the rows you're adding and can call .addClass:
var tbl = $("#table1");
$('<tr></tr><tr></tr><tr></tr>').appendTo(tbl).addClass("test")
You could also put the class in the string then append it or modify it (add a class) prior to appending it. Note how I only have one tr in my string but append it multiple times (optionally adding a class as noted)
var tbl = $("#table1");
var tr = '<tr class="test"></tr>';
var td = '<td class="test">new data</td>';
//var addedrow = $(tr).append(td).addClass("newclass");//adds class to the row
var addedrow = $(tr).append(td);//create new row object
addedrow.find('td').addClass("newclass"); //adds class to the td in the new row
var ar2 = $(tr).append(td);
var ar3 = $(tr).append(td);
tbl.append(addedrow, [ar2, ar3]); // appends the new rows
tbl.find('tr').last(td).addClass("newclass");//add class to last rows td
see it in action here: http://jsfiddle.net/MarkSchultheiss/0osLfef3/

jQuery isn't creating table row elements

I'm creating a JavaScript progress bar and the bar itself and the detail message are inside a table. Now, I'm creating this so that all that needs to be in the page is a div and then the class will fill in the rest when it's created. Since it's in a table, the bar and message are supposed to be on different rows, however when I try to create the rows with jQuery they aren't getting generated and the only thing that is getting put in the tables is the two td elements.
The code I currently have is down below. I've tried several different methods to accomplish it that I thought would work.
I have tried using .wrap('<tr></tr>') to try and get it before I put it in the table, and in the call for the table too (i.e. tdMessage.wrap('<tr></tr>') and tdMessage.wrap('<tr></tr>').html()).
I have tried both document.createElement('tr') and just $('<tr></tr>') and calling .html() when putting it in the table.
I feel like there was another attempt in there too...but I can't think of what it was.
var tdMessage = $(document.createElement('td'));
tdMessage.prop('id', this.MessageId.substr(1));
tdMessage.css('text-align', 'center');
//tdMessage.wrap('<tr></tr>');
//var trRow2 = $(document.createElement('tr'));
var trRow2 = $('<tr></tr>');
trRow2.html(tdMessage);
tdMessage = null;
var divBar = $(document.createElement('div'));
divBar.prop('id', this.BarId.substr(1));
divBar.css('width', '0%');
divBar.css('height', '15px');
divBar.css('background', 'url(images/LoadingBarBG.gif)');
var tdBar = $(document.createElement('td'));
tdBar.css('border', '1px #B0B1B1 solid');
tdBar.css('padding', '1px');
tdBar.html(divBar);
//tdBar.wrap('<tr></tr>');
divBar = null;
//var trRow1 = $(document.createElement('tr'));
var trRow1 = $('<tr></tr>');
trRow1.html(tdBar);
tdBar = null;
var tblInner = $(document.createElement('table'));
tblInner.prop('width', '400');
tblInner.prop('cellpadding', '0');
tblInner.prop('cellspacing', '0');
tblInner.prop('border', '0');
tblInner.html(trRow1.html() + trRow2.html());
trRow1 = null;
trRow2 = null;
I'm probably just missing something, but I can't for the life of me figure it out. Everything looks like it should work, and everything else seems to be.
Also, the HTML that it keeps generating is either just putting both td elements in the table without the tr elements surrounding them or it will even just put the bars td and omit the message one.
Thanks for any help.
Don't use .html() because everything you have is a jQuery object, not raw HTML, instead append the cell to the row:
trRow2.append(tdMessage);
trRow1.append(tdBar);
Then append the rows to the table:
tblInner
.append(trRow1)
.append(trRow2);
Do the same with your div when you want to insert it into the cell:
tdBar.append(divBar);

Jquery Mobile Table Reflow

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

Deleting all the clone node of a table row in javascript

function newRow(t) {
var parent = t.parentNode.parentNode.parentNode;
var row = t.parentNode.parentNode.cloneNode(true);
row.firstChild.nextSibling.firstChild.setAttribute('value', 'sumit');
parent.appendChild(row);
}
function removeRow(t) {
var y = t.parentNode.parentNode;
y.parentNode.removeChild(y);
}
the above code is working fine but i want to delete all the clones at once which are created by above code on a onchange event of a select box
Just add a class name to the cloned elements which would allow you to search for them and delete them later:
var row = t.parentNode.parentNode.cloneNode(true);
row.className += ' clonedrow';
...
// Remove all the cloned rows
var clonedRows = document.querySelectorAll('.clonedrow');
for (var i = 0; i < clonedRows.length; i++) {
clonedRows[i].parentNode.removeChild(clonedRows[i]);
}
Once the cloned rows have been added to the DOM, they look (to JavaScript) just like the original rows.
Since you're just appending cloned rows to the table body, what I would do is as follows:
Outside the functions, as soon as the document loads, use .childNodes.length to get the number of rows in your table and store it globally in, say, lastpos.
When you need to delete the clones, start at .childNodes[lastpos] and remove nodes until the table has lastpos rows again.

Categories

Resources