I have a table where the cell content is editable.
Now I want, after I finished editing the table, the html code from the table with all values.
Here is a table:
<table class="table table-bordered content">
<thead>
<tr>
<th>bla</th>
<th>bla bla</th>
<th>bla bla bla </th>
<th>more bla</th>
</tr>
</thead>
<tbody>
<tr contenteditable="true">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr contenteditable="true">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<button id="save">Save</button>
That's my JS code:
$('#save').on('click', function () {
var table = $('.content').html();
alert(table);
});
The problem is that if I console.log the table variable I get this output:
<thead>
<tr>
<th>bla</th>
<th>bla bla</th>
<th>bla bla bla </th>
<th>more bla</th>
</tr>
</thead>
<tbody>
<tr contenteditable="true">
<td>dwad</td>
<td>dwada</td>
<td>dawdaw</td>
<td>dawdaw</td>
</tr>
<tr contenteditable="true">
<td>daw<br></td>
<td>daw<br></td>
<td>dwadaw<br></td>
<td>daw<br></td>
</tr>
</tbody>
If you have a closer look you can see that the
<table class=" ... "> and the </table> tag are gone but I also need them.
Does someone know what I can do to also get the table-tags ?
Try this:
var table = $('.content')[0].outerHTML;
alert(table);
Should work in every browser
Use outerHTML on the node element. Like this:
$('#save').on('click', function () {
var table = $('.content')[0].outerHTML;
alert(table);
});
Use outerHTML
$('.content').get(0).outerHTML
Check the example on JSfidle
$('#save').on('click', function () {
var table = $('.content')[0].html();
alert(table);
});
This should work.
Use Element.outerHTML
The outerHTML attribute of the element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can be set to replace the element with nodes parsed from the given string.
$('#save').on('click', function () {
var table = $('.content');
alert(table.get(0).outerHTML);
});
Related
I have a form with several input fields including WYSIWYG editor as an input field. In WYSIWYG editor user enter data using HTML table. But sometime happen while adding new row user enter new table snippet within in the same row as in the below code.
<table width="100%">
<tbody>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>
<table width="100%">
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
How can I validate this HTML code snippet using Javascript? How can I identify that within or in table tag (<table) exist. Any help would be appreciated.
You can create an element out of your HTML like this:
function htmlToElement(html) {
var template = document.createElement('template');
html = html.trim(); // Never return a text node of whitespace as the result
template.innerHTML = html;
return template.content.firstChild;
}
const myTable = htmlToElement('<table width="100%">....</table>');
... and then check if there is a table within the table:
if (myTable.querySelector('table')) {
// ...
}
Credits for the htmlToElement function: Creating a new DOM element from an HTML string using built-in DOM methods or Prototype
I have the following structure in my HTML in an angular 7 application:
What I am trying to do is to call the GetContent() function on click of any of the text inside the div. I am able to get the $event as "Liquidity" when I click on the text but if I click on any empty space between the text, the $event is empty. I tried every possible permutation of changing the location of the function call and id but same issue. Can anyone let me know what is wrong.
<tr (click)="GetContent($event)">
<td>
<table>
<tbody>
<tr>
<td>
<div id="Liquidity"> lot of text....................... </div>
</td>
</tr>
</tbody>
</table>
</td>
<tr>
Because there is no content in your TR's and TD's, its not creating a space at all. Look at my code, I have added padding for table row's ,table and table data tags
<table>
<tbody>
<tr (click)="GetContent($event)" >
<td style="padding:20px;background:red">TD
<table style="padding:20px;background:green">Table
<tbody>
<tr>
<td style="padding:20px;background:blue">TD
<div id="Liquidity" style="padding:10px;background:green"> lot of text....................... </div>
</td>
</tr>
</tbody>
</table>
</td>
<tr>
</tbody>
</table>
example stackblitz
Do it this way ,
UPDATED
<table>
<tbody>
<tr>
<td>
<div id="Liquidity" (click)="GetContent($event)"> lot of text....................... </div>
</td>
</tr>
</tbody>
</table>
ts file
GetContent(event) {
var target = event.target || event.srcElement || event.currentTarget;
var idAttr = target.attributes.id;
var value = idAttr.nodeValue;
console.log(value) //you will get liquid here.
}
I have 2 pages and 2 tables, in page 1(table 1) I want to send selected rows to page 2(table 2) where in table 2 I show the selected rows
This is the first table in page 1:
<table class="src-table">
<tr>
<th>Select</th>
<th>Firstname</th>
</tr>
<tr>
<td>
<input type="checkbox">
</td>
<td>Jill</td>
</tr>
<tr>
<td>
<input type="checkbox">
</td>
<td>Eve</td>
</tr>
</table>
<br>
<input type="button" value="Submit" id="submit">
Like image below
This is the second table in page 2:
<table class="target-table">
<tr>
<th>Select</th>
<th>Firstname</th>
</tr>
</table>
Like image below
If you really need this. You can use localStorage.
localStorage not working in the sandbox. But you can use it your application as well.
run storeItems when you need to save selected to store (for example on element select)
run appendStoredToAnouther on window event window.onload on page with the target table
function storeItems() {
const selectedItems = document.querySelectorAll("#first-table .selected");
const selectedHtml = nodeListToString(selectedItems);
localStorage.add('selectedTableItems', selectedHtml);
}
function nodeListToString(nodeList) {
let string = '';
nodeList.forEach(function(node) {
string += node.outerHTML;
});
return string;
}
function appendStoredToAnouther() {
const itemsHtml = window.localStorage.get('selectedTableItems');
const targetTable = document.getElementById('target-table');
targetTable.innerHTML = itemsHtml + targetTable.innerHTML;
}
<table id="first-table">
<tr class="selected">
<td>1</td>
<td>Selected</td>
<td>Item</td>
</tr>
<tr class="selected">
<td>1</td>
<td>Selected</td>
<td>Item</td>
</tr>
<tr>
<td>2</td>
<td>Not Selected</td>
<td>Item</td>
</tr>
</table>
<button type="button" onclick="storeItems()">Send to anouther</button>
<button type="button" onclick="appendStoredToAnouther()">Append stored to anouther</button>
<table id="target-table">
<tr class="selected">
<td>1</td>
<td>Selected</td>
<td>Item</td>
</tr>
<tr>
<td>2</td>
<td>Not Selected</td>
<td>Item</td>
</tr>
</table>
Below I demonstrated how some lines could be carried over from one table to another one on a following page. However, since both pages are probably hosted on the same server it is in most cases more practical to first collect some unique identifiers for the selected table records, transmit them to the next page and then get the actual table contents from the original data source again (in many cases a database table or view). This approach will also make your page safer against unauthorised injections.
In case that the tables are to be shown in two consecutive pages you can do the following:
// shortcut for utility function querySelectorAll():
const qsa=(s,o)=>[...(o||document)['querySelectorAll'](s)];
const log=qsa('#log')[0];
qsa('#submit')[0].addEventListener('click',function(){
var dat="tbl="+JSON.stringify(
qsa('tr',qsa('.src-table')[0]).filter(tr=>qsa('input:checked',tr).length)
.map(tr=>qsa('td',tr).slice(1)
.map(td=>td.innerHTML))
);
log.innerHTML+="<hr>dat:"+dat;
log.innerHTML+="\nwindow.location=\"page2.html?\"+encodeURIComponent(dat)";
// this second part would be placed in the onload section if the next page:
log.innerHTML+='var dat=window.location.search.substr(1)'
var args=dat.split("&").reduce((a,v)=>{
var t=v.split('=');
a[t[0]]=JSON.parse(decodeURIComponent(t[1]));
return a;},
{}
);
qsa('.trg-table')[0].innerHTML+=
args.tbl.map((r,i)=>'<tr><td>'+(i+1)+'</td><td>'+r.join('</td><td>')+'</td></tr>').join('');
})
<h2>page one</h2>
<table class="src-table">
<tr><th>Select</th><th>Firstname</th><th>Familyname</th></tr>
<tr><td><input type="checkbox"></td><td>Jill</td><td>Jones</td></tr>
<tr><td><input type="checkbox"></td><td>Eve</td><td>Adams</td></tr>
</table>
<br>
<input type="button" value="Submit" id="submit">
<h2>this would be the second page</h2>
<table class="trg-table">
<tr><th>no</th><th>Firstname</th><th>Familyname</th></tr>
</table>
<pre id="log"></pre>
As this is a sandbox the last lines had to modified a bit. In your page you should actually redirect your page with the window.location assignment.
On the second page you then need to read the passed information from window.location.search and use that information to append it to your table there.
I tried to use cloneNode mentionned here Copy the content of one table into another but Chrome says cloneNode is not a function
https://jsfiddle.net/4wczdykc/1/
<table>
<thead>
<tr>
<th scope="col" colspan="1">TABLE TO CLONE</th>
</tr>
<tr>
<th>Column</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
script:
myTable = document.getElementsByTagName("Table")[0];
myClone = myTable.cloneNode(true);
document.body.appendChild(myClone);
The getElementsByTagName() method accesses all elements with the specified tagname.So you have to select the first element of the NodeList. So passed [0] to select it.
myTable = document.getElementsByTagName("table")[0];
myClone = myTable.cloneNode(true);
document.body.appendChild(myClone);
WORKING FIDDLE
I have a table structure like this. Fairly simple one.
<table id="myTable" class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
</tr>
</tbody>
</table>
At runtime I am binding a new row to this table for a particular rowclick. This new row contains a new table.
Now on clicking the row again, I want to be able to remove the newly added row(the new table).
I am using bootstrap table.
Here is what I have tried so far.
$('#myTable').on('click-row.bs.table', function (e, row, $element) {
//if ($element.has('#newlyAddedTable').length) { ....// did not work
if ($('#myTable').has('#newlyAddedTable').length) { // this removes the table on any row click. Not what I intend to do
{
$("#newlyAddedTable").remove();
} else {
// some operation...
}
}
I want to be able to remove the newly added table on the row it was created.
Just more explanation based on the Answers below:
<tr> ----------> if i click this
<td>
<table id="newlyAddedTable"> ---------> this is added
</table>
</td>
</tr>
<tr> ----------> if i again click this or maybe any other row in the table
<td>
<table id="newlyAddedTable"> ---------> this is removed
</table>
</td>
</tr>
Update: from OP's comment below it sounds like the best way to implement the new table is to use a class selector and not an id selector. The code below has been updated accordingly. ***Where previously there was an id for newTable there is a class ---> #newTable ===> .newTable:
Just change:
$('#myTable').has('#newlyAddedTable').length
To:
$('.newlyAddedTable', $element).length //element === clicked row -- see demo
vvvvv DEMO vvvvv
$('#myTable').bootstrapTable().on('click-row.bs.table', function(e, row, $element) {
if( $('.newTable', $element).length ) {
$('.newTable', $element).remove();
} else {
$('td:first', $element)
.append( '<table class="newTable"><tr><td>NEW TABLE</td></tr></table>' );
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.7.0/bootstrap-table.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.7.0/bootstrap-table.min.css" rel="stylesheet"/>
<table id="myTable" class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
</tr>
</tbody>
</table>
Try replacing your remove code with this:
$(document).on("click", "#newlyAddedTable", function(){
$(this).remove();
});
The code above registers a click listener on the document. The second parameter filters those events for those with the target #newlyAddedTable. This way you don't have to register a new click handler every time you insert a row (as in #VimalanJayaGanesh's solution).
P.S. If you are adding HTML that looks like this:
<tr>
<td>
<table id="newlyAddedTable">
</table>
</td>
</tr>
Then you are probably actually wanting to remove the parent tr (not the table with the id). There are two ways to fix this.
You can change the selector that filters click events and so have the tr handle the click rather than the table element in my example code:
$(document).on("click", "tr:has(#newlyAddedTable)", function(){
You can leave the selector as is but grab the parent tr from the table and remove that changing the remove line above to:
$(this).parents("tr").first().remove()
or
$(this).parent().parent().remove()
As I don't have your complete code / fiddler, here is a possible solution.
Are you looking for something like this?
$('#add').on('click', function()
{
var newRow = '<tr CLASS="newrow"><td colspan="3"><table><tr><td>Test</td><td>User</td><td>test#example.com</td></table></td></tr>'
$('#myTableBody').append(newRow);
Remove()
});
function Remove()
{
$('.newrow').off('click').on('click', function()
{
$(this).remove();
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="myTable" class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody id="myTableBody">
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
</tr>
</tbody>
</table>
<button type='button' id='add'>Add</button>
Note:
The following line indicates that,
$('.newrow').off('click').on('click', function()
the click event will be binded to the new row only once.
The reason for adding 'off('click') is, when you are dynamically adding rows (with common class 'newrow') to the table, the events will be binded several times. To avoid that, remove the previously binded click event and add a new one.