Copy HTML Table to Text Box Using JQuery/JS - javascript

My problem has left me trying many solutions and stumped for a while now. My problem is exactly this:
There's a HTML table and a button on a page. Upon pressing the button, a script will run, copying the contents of the cells in the table into a text box. Here is the code for the table:
<table>
<tr><th></th><th>Category1</th></tr>
<tr><td>1.</td><td class="rule">Rule1</td></tr>
<tr><td>2.</td><td class="rule">Rule2</td></tr>
<tr><th></th><th>Category2</th></tr>
<tr><td>3.</td><td class="rule">Rule3</td></tr>
<tr><td>4.</td><td class="rule">Rule4</td></tr>
<tr><th></th><th>Category3</th></tr>
<tr><td>5.</td><td class="rule">Rule5 </td></tr>
<tr><td>6.</td><td class="rule">Rule6</td></tr>
<tr><td>7.</td><td class="rule">Rule7</td></tr>
<tr><th></th><th>Category4</th></tr>
<tr><td>8.</td><td class="rule">Rule8</td></tr>
</table>
My first thoughts were to write a script that iterated through the table and copied the contents of each cell (and creating a new line after every 2 cells). I realized very quickly, that I had no idea how to do that. After some searching I was able to come up with a script that clones the table, and it actually works quite well. This code is here:
$("button").click(function () {
$("table").clone().appendTo(".copy");
});
There are two problems that arise from using this method, however. I want plaintext, not a carbon copy of the table. The other problem is that this method only works when I clone the table into a div, it will not work when I try to clone it to a text box.
I've searched for a while for something similar to this and can only find solutions to copying single rows or cells. I had originally started there but couldn't figure out a way to write a loop that started at the beginning of the table and iterated through the entire thing, copying the contents as it iterated row by row (and creating a new line with each new row that it encountered). The loop would obviously end when there were no more rows to iterate through... This all sounds so simple to do, I know there must be a way.
Please Note: This script will be applied to a Site.Master Page so the script must be able to run for a plethora of tables. All of the tables follow the same structure shown above, but some will have more rows than others.
Any ideas? Any help is greatly appreciated.

You could use the .each() JQuery Method:
JS
function cloneTableContents()
{
$("table tr").each(function()
{
$(this).children().each(function()
{
$(".copy").append($(this).text());
});
});
}
JS For All Tables On Page In Order
function cloneTableContents()
{
$("table").each(function()
{
$(this).find("tr").each(function()
{
$(this).children().each(function()
{
$(".copy").append($(this).text()+" ");
});
});
});
}
HTML
<table id="mine">
<tr><th></th>
<th>Category1</th>
</tr>
<tr><td>1.</td><td class="rule">Rule1</td></tr>
<tr><td>2.</td><td class="rule">Rule2</td></tr>
<tr>
<th></th>
<th>Category2</th>
</tr>
<tr><td>3.</td><td class="rule">Rule3</td></tr>
<tr><td>4.</td><td class="rule">Rule4</td></tr>
<tr>
<th></th><th>Category3</th>
</tr>
<tr><td>5.</td><td class="rule">Rule5 </td></tr>
<tr><td>6.</td><td class="rule">Rule6</td></tr>
<tr><td>7.</td><td class="rule">Rule7</td></tr>
<tr>
<th></th><th>Category4</th>
</tr>
<tr><td>8.</td><td class="rule">Rule8</td></tr>
</table>
<textarea class="copy"></textarea>
<button onclick="cloneTableContents('mine','.copy');">Copy</button>
Working Example:
http://casewarecomputers.com:8088/soHelp.html

Related

How to hide a row of a table which does not contains a specific icon

I have a table with some items and those items can be selected by adding a tick. Check the image attached:
What I need to achieve is to hide the row which does not contain any ticks to be not visible. This is because in my app I have to generate lists of the items contains only ticks in another view. So when I will press the generate button that row will be hidden.
I just want to say if that row does not contain any 'glyphicon-ok' need to be deleted/hidden when I will generate the view with the list of those items.
I tried something like this:
SveCrf.prototype.hideRowWhereNoTicksForm = function () {
var tr = document.getElementsByTagName('tr');
for (var i = 0; i < tr.length; i++) {
switch (tr.item(i).getElementsByTagName('td').item(0).className) {
case "glyphicon-ok":
tr.item(i).style.display = "none";
break;
}
}
}
This doesn't do anything.
I would like to see an example of being able to resolve this issue.
Correct me if I'm wrong but you don't seem to have provided HTML you want to act upon but just a screenshot and a link to some RoR code in the comments that generates the HTML. Also you don't show how you try to execute SveCrf.prototype.hideRowWhereNoTicksForm, and furthermore I'm not really sure at all what you are trying to do with switch/case (I also don't understand what item is supposed to be; this is where providing us with actual HTML might have helped).
In addition, as I've alluded to in some comments of mine, you are really trying to do two things. I don't know if you've seen this Stackoverflow page yet about creating "a Minimal, Complete, and Verifiable example" but I think reviewing that will help improve your StackOverflow experience moving forward (and also for me it validated my suggestion of "divide and conquer").
All of which I think made it hard for you to get the help you desired. In any case below I'm providing some sample HTML with a table containing four rows total, two with a cell that contains the class foo, and two that don't. Beneath that is my non-jQuery code selecting the rows with no cells containing the class foo, and then hiding them; furthermore there is a demo of the same functionality using jQuery at https://repl.it/#dexygen/HideRowsWithNoCellsWithClass
<table border="1">
<tr><td class='foo'>foo</td><td></td><td></td></tr>
<tr><td></td><td>bar</td><td></td></tr>
<tr><td></td><td></td><td>baz</td></tr>
<tr><td class="foo">foo</td><td>bar</td><td>baz</td></tr>
</table>
/*
We cannot call `filter` directly on an HTMLCollection such as returned by
"document.getElementsByTagName('tr')" as it is not a bona fide array, so we use
"[].filter.call()", and we return only those rows that *fail* the test
"row.querySelector('td.foo')", then we loop over these with `forEach` and hide them
*/
[].filter.call(document.getElementsByTagName('tr'), function(row) {
return !row.querySelector('td.foo');
}).forEach(function(row) {row.style.display = 'none'});

Assign id's (1,2,..etc) to a dynamic html table

Trying to achieve functionality in the linked picture.
The table grows as users click on the add button. I'm trying to replace the text inside the first column of the newly added td with the length of the table. I'm new to jQuery and not sure how to do that. Any help would be great.
It will be easier to answer you with your code but you can know the added row number with $('#yourTBodyID > tr').length
Have a look to this code :
HTML
<table>
<thead>
<tr>
<th>Zone ID</th>
<th>Zone Description</th>
<th><button onclick="addRow();">Add Row</button></th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
JS :
function addRow() {
var rowNum = $('#tableBody > tr').length + 1;
$('#tableBody').append('<tr>'
+ '<td>' + rowNum + '</td>'
+ '<td><input type="text"/></td>'
+ '<td><button>Disable</button></td>'
);
}
jsFiddle
Hope it helps ;)
You'll face a few more problems, more than just showing the number on the recently created tr. As you don't write down any code, I'm note sure at which point of the development you are, or which functionalities have you created already. I'll briefly try to explain how to achieve it, just showing you the path.
Add button should find in the DOM a valid <tr>to .clone(). It could be a "seen tr" or a template one. In the first situation you should clean the information in the input.
Once you have saved that cloned node into a variable, you should prepare it for insertion.
Counting the <tr> lines (it'd help if you have a classname on them) and assign the .length() to the first <td> using .text()
Changing name attribute on the input inside the second <td>tag. Otherwise when the form is sent to the server, you will loose every input with the same name which prior the last one.
On the last <td> tag you have a disabled button. It won't have any attached event on your brand new element. You can attach it here, or if you prefer, you can add the event on the very beginning using something like $('table').on('click','.disable-button',function(e){}). Doing that instead of $(.disable-button).click() will assure you that elements with this class created after DOM .ready()fires up will get this event.
I hope it helped you

Ordering of Columns in html using javascript or jquery

I am facing a problem on getting a solution on Ordering of Columns. I have used many 3rd party libraries like danvk library,jqGrid for dragging the columns. But what i want to do is. I have a div and have five fields in it. {FirstNJame,LastName,Address,Phone,Designation} also having up and down button so that i can move the fields up and down. On the Ok button, I want to have my table order according the order of fields which i have set on that div. so in short, change in thead and tbody, of what kind of order has been set in that div. Ihave programmed up and down, back and forward. I just need a solution to move the column position in javascript or in jquery. Thanks.
This should get you going: http://jsfiddle.net/S9ykD/
The code (using jQuery):
var order = [0,2,1,3];
$(function() {
$("table tr").each(function() {
var orderedTds = new Array();
for (var i=0; i<order.length;i++)
orderedTds[i] = $(this).children("td")[order[i]];
for (var i=0; i<order.length;i++)
$(this).append(orderedTds[i]);
});
});
this is the sample markup :
<table>
<tr>
<td>aaa</td>
<td>bbb</td>
<td>ccc</td>
<td>ddd</td>
</tr>
<tr>
<td>111</td>
<td>222</td>
<td>333</td>
<td>444</td>
</tr>
</table>
Just use some js library - I recommend to use Datatables, which is very nice and you can accomplish almost everything and is very cusotmizable. Or use whatever you are used to. Then just handle the click event on the button and send the configuration to the library. This can be done pretty well with Datatables. See fnSort or fnSortListener in the Datatables API doc.

Make one div containing a table into two divs containing tables

I have a function that gets raw HTML to output to a table, but I want to take out the first three columns and put them in another div.
I am considering making a div on the page that is hidden, setting this div's html to the raw HTML I get, and then using the selector syntax to strip it into each table's div. Is there a way to do this without the intermediate faux-div to hold the raw HTML?
It all depends out what the "function that gets raw HTML" does. Where is it getting the HTML? If it's in some kind of format other than a rendered node, then you should be able to manipulate it as needed prior to rendering it. If you've got it in a string format (and the markup is valid) jQuery is really good at turning strings into traversible objects. For example:
var xml = '<div><span>hello</span></div>';
console.log($(xml).find('span'));
In FireBug, this displays the span as an object node.
I'm not sure exactly why you'd want to do this, rather than arrange your data server-side, but one approach that works is:
$(document).ready(
function(){
$('table').click(
function(){
$('<table />').appendTo('#newTable').addClass('new');
$('table').eq(0).find('tr td:first-child').each(
function(){
$(this).appendTo('.new').wrap('<tr></tr>');
});
});
});
With the (x)html:
<table>
<tr>
<td>1:1</td>
<td>1:2</td>
<td>1:3</td>
</tr>
<tr>
<td>2:1</td>
<td>2:2</td>
<td>2:3</td>
</tr>
<tr>
<td>3:1</td>
<td>3:2</td>
<td>3:3</td>
</tr>
<tr>
<td>4:1</td>
<td>4:2</td>
<td>4:3</td>
</tr>
</table>
<div id="newTable"></div>
JS Fiddle demo
The demo uses jQuery's click() event, but that's just to show it working interactively; it could certainly be placed straight into the DOM-ready/$(document).ready(function(){/* ... */}); event.
The above code would allow repeated clicks (each time moving the first 'column' into a new table), the edit removes that possibility using jQuery's one(), giving the following jQuery:
$(document).ready(
function(){
$('table').one('click',
function(){
$('<table />').appendTo('#newTable').addClass('new');
$('table').eq(0).find('tr td:first-child').each(
function(){
$(this).appendTo('.new').wrap('<tr></tr>');
});
});
});
JS Fiddle demo, featuring one().

How do you make a draggable <tr> using YUI3?

I'm using YUI3 and I've been trying to make <tr> tags inside a table draggable with no luck. I've found that I can drag <div> nodes around, but for some reason I can't drag a <tr>. It shouldn't be a limitation, I've found examples of YUI2 where this is done, but the code is completely different from YUI3 and I can't figure this out.
Does anyone know if you can drag <tr> nodes in YUI3, and how to do this?
Here's my code:
YUI({combine: true, timeout: 10000}).use("dd-drop", "dd-constrain", "node", function (Y) {
var drags = Y.Node.all('#draftable-players tr.drag');
drags.each(function(v, k) {
var dd = new Y.DD.Drag({
node: v,
dragMode: 'intersect'
}).plug(Y.Plugin.DDConstrained, {
constrain2node: '#draft'
});
dd.on('drag:end', function(e) {
e.preventDefault();
});
});
});
And the relevant HTML:
<div id="draft">
<table id="draftable-players">
<tr class="drag"><td>some stuff</td></tr>
<tr class="drag"><td>some more stuff</td></tr>
</table>
<table> another table, i'm trying to drag <tr>s from the other one to this one
</table>
</div>
Any help would be appreciated. Thanks!
This question didn't garner too much interest, but I thought I'd answer it just as well in case someone comes across this in the future.
I found that you can't drag <tr> elements between two tables, only within the same table - further inspection of the YUI2 examples I mentioned above were doing exactly this, dragging within a given table.
I've since converted my tables to <div> elements and styled them to look like a <table> using CSS, and now I can drag from one 'table' to another. If anyone is curious to see some code for dragging and dropping, check out YUI3's docs here.

Categories