Copy grid lines when user copies the grid from webpage and paste it into notepad

540 views Asked by At

The user would like to have the grid lines copied with the grid data when he copies from the web page. Is that possible ?

currently the result of copying is something like:

name subject
lolo math
fofo history

what I want to have is:

  |  name | subject |
   ---------------
  |  lolo | math    |
   ---------------
  |  fofo | history |

I googled that but I couldn't find a good solution for that, and I'm not experienced in front-end tricks.

3

There are 3 answers

0
user181452 On BEST ANSWER

My solution was a mix of the solutions above use Clipboard.js and parse the copied text:

  new Clipboard('.clipboard-btn', {
    text: function (trigger) {
      var originaltext = $(trigger).next('table').closest("#my-tbl").text();
      return addTableLines(originaltext);
    }
  });

I'm still writing addTableLines because the split is not detecting the new lines.

0
Lajos Arpad On

You need to create a copy event to your table:

//Here we assume that your table has an id and it is stored in myTable
document.getElementById(myTable).addEventListener('copy', function(e){
    e.preventDefault();
    e.clipboardData.setData("Text", parseClipboard(e.clipboardData.getData("Text")));
});

In the example above parseClipboard is assumed to handle your text in the clipboard and convert it as you will. You would want to split the text with newline as separator, add your | characters at the start and end of the line for each item (line) and then join them with the separator of newline---------------newline

1
Ivozor On

You can do something like this:

function changeCopiedText(event) {
    event.preventDefault();

    // get original text from selection
    var originaltext =  window.getSelection();

    // call your function to add the lines to the original text
    var textwithlines = addTableLines(originaltext);

    // add the new text to the clipboard
    if (window.clipboardData) {
        window.clipboardData.setData('Text', textwithlines);
    }
}

// capture the copy event
document.addEventListener('copy', changeCopiedText);

But you will have to think about the best way to add the lines in addTableLines, according to your needs.