1

i have this simple function in which i try to pass an array to the clipboard in order to paste in in excel later on

hiddenInputOnCopyHandler = ev => {    
    ev.clipboardData.setData('text/plain', ev.currentTarget.value.split(','));
    ev.preventDefault();
  };

but i'm getting a string instead, i guess because the type passed in the setData is 'text/plain' but i couldn't find better in its documentation

now the problem is that when it's pasted in excel , the whole serialized array will take only one cell enter image description here

4
  • Do you want the result in the clipboard to look like the array elements concatnated together or something like ["a","b","c"]? Commented Aug 12, 2020 at 9:12
  • yes i want it an array like ["a","b","c"] Commented Aug 12, 2020 at 9:15
  • 1
    you should try tab \t instead of comma ,, (reference) ev.currentTarget.value.split(',').join('\t') Commented Aug 12, 2020 at 9:16
  • thanks @hgb123, please rewrite your comment as an answer Commented Aug 12, 2020 at 9:38

2 Answers 2

1

According to the docs, you should fire a copy command to copy the selection to clipboard. Also you should check for browser compatibility.

Also currentTarget.value gives undefined so you should use textContent instead.

When you click on paragraph, then it fires the copy command in copyAction function and then eventListener with copy event executes the hiddenInputonCopyHandler function.

function init(){

   let el = document.getElementById("CpToClip");
    el.addEventListener('click',copyAction);
    
    el.addEventListener('copy', hiddenInputOnCopyHandler);
    
}

function copyAction(){
   document.execCommand('copy');  
}

hiddenInputOnCopyHandler = ev => {
    let copiedVal = ev.currentTarget.textContent.trim().split(',').join('\t');
    
    console.log(copiedVal);// "HHHhhh" "mkjf" "Tendue" "Bonne" "10-07-2020" "[email protected]"    
    
    ev.clipboardData.setData('text/plain', copiedVal);
    ev.preventDefault();
}


addEventListener('load',init);

Html

<p id="CpToClip">
   HHHhhh,mkjf,Tendue,Bonne,10-07-2020,[email protected]
</p>

Check my solution and let me know.

Sign up to request clarification or add additional context in comments.

2 Comments

i did call document.execCommand('copy'); but it didn't update the clipboard content and i had to add that paste handler that i mentionned in my question to re-do it there (and it finally worked)..
@Bardelman As you can see from my code, you should click the p tag in order to copy the content. You can modify it as you wish, check my updated answer.
0

You should try tab \t instead of comma , (reference)

ev.currentTarget.value.split(',').join('\t')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.