Valentin BEAULE Valentin BEAULE - 6 months ago 33
jQuery Question

Select the value of a TD on click to ease copy

I want to select onclick the innerHTML of a td so the user can just do ctrl+C to copy the content.

I tried many combination and I can't find a way. However it seams to work on inputs with a simple

document.getElementById(id).select();


Adding a focus don't effect anything, and the .select() send and error:


document.getElementById(...).select is not a function


So how can I do with a td element?
I don't mind if it's not working on IE.

Answer

You can select text of td when it clicked.

$("td").click(function(){
    var range = document.createRange();
    range.selectNodeContents(this);  
    var sel = window.getSelection(); 
    sel.removeAllRanges(); 
    sel.addRange(range);
});
table, tr, td {
    border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
        <td>Column1</td>
        <td>Column2</td>
        <td>Column3</td>
    </tr>
    <tr>
        <td>Column1</td>
        <td>Column2</td>
        <td>Column3</td>
    </tr>
</table>