Jquery contenteditable for all cells not rows - javascript

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

Related

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 Dynamically create div, populate tbody and append to existing div

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.

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

Get An Element Within a Table Row

Firstly,
If possible, I would like to do this without JQuery, and purely Javascript.
Ok so I have an html table with rows getting added dynamically to it.
In each row is a:
Select Element (id = "ddFields")
Text Input Element (id = "tfValue")
Button Element (no id)
The Button Element removes the row for which it is situated
The Select Element has a default option of "" and then other 'valid' options
The Text Input is added to the row but it is hidden.
All elements are in the same
Basically I would like for the Select Element to show the hidden text input element if the selected index is != 0
so far I have this for my onchange function:
function itemChanged(dropdown) //called from itemChanged(this)
{
var cell = dropdown.parentNode;
var row = cell.parentNode;
var rowIndex = dropdown.parentNode.parentNode.rowIndex;
var index = dropdown.selectedIndex;
var option = dropdown.options[dropdown.selectedIndex].text;
if(index >0)
{
alert(row);
var obj=row.getElementById("tfValue"); //tfValue is the Text Field element
alert(obj);
//row.getElementById("tfValue").hidden = "false"; //doesn't work
//row.getElementById("tfValue").setAttribute("hidden","true"); //doesn't work
}
else
{
alert('none selected');
}
}
Finally figured it out. So here it is:
SCENARIO:
A table that has rows added to it dynamically.
In each row there is a select element and an input text element.
The select element changes text-value of the input text element based on the index of the select element.
in your select element set the onchange function to this:
onchange="selectionChanged(this)"
then create a javascript function shown below:
function selectionChanged(dropdown)
{
//get the currently selected index of the dropdown
var index = dropdown.selectedIndex;
//get the cell in which your dropdown is
var cell = dropdown.parentNode;located
//get the row of that cell
var row = cell.parentNode;
//get the array of all cells in that row
var cells = row.getElementsByTagName("td");
//my text-field is in the second cell
//get the first input element in the second cell
var textfield = cells[1].getElementsByTagName("input")[0];
//i use the first option of the dropdown as a default option with no value
if(index > 0)
{
textfield.value = "anything-you-want";
}
else
{
textfield.value = null;
}
}
Hope this helps whoever. It bugged me for a very long time. Thanks shub for the help! :)
first, I hope you are not repeating your ids. No two items should have the same id.
If you're iterating, create id1, id2, id3.
Also, this is not necessary but I suggest introducing your vars like this:
var a = x,
b = y,
c = z;
If you decide to use jQuery you could just do this:
$('#tableid').on('click','button',function(){
$(this).parent().parent().remove();
});
$('#tableid').on('change', 'select',function(){
if($(this).val()){ $(this).next().show(); }
});
Be sure to change #tableid to match your table's id.
This assumes the text input is the very next element after the select box. If not so, adjust as necessary or ask and I'll edit.

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