1

Can we select all table td by pressing CTRL+A button using jQuery or javascript?

Cœur
  • 37,241
  • 25
  • 195
  • 267
manishjangir
  • 1,605
  • 6
  • 24
  • 27

2 Answers2

1

Yes you can, and you are gonna have to do it programmatically.

Here is an example: Handling Keybord Shortcuts in Javascript

And yes, this is a good question.

Daniel Ribeiro
  • 10,156
  • 12
  • 47
  • 79
0

You can use this function to catch Ctrl+A or Ctrl+a.

$("body").keydown(function(e) {
    if (e.ctrlKey && (e.keyCode == 65 || e.keyCode == 97)) {
        selectText('copyme');
        e.preventDefault();
    }
});

This function will work in Firefox and Chrome. The old version used keypress() function and e.charCode and didn't work in newer version of Chrome.

The only issue is with selecting text. I've borrowed the function selectText() from this answer https://stackoverflow.com/a/987376/446792

Here is a working demo:

$(document).ready(function() {

    function selectText(element) {
        var doc = document;
        var text = doc.getElementById(element);

        if (doc.body.createTextRange) { // ms
            var range = doc.body.createTextRange();
            range.moveToElementText(text);
            range.select();
        } else if (window.getSelection) { // moz, opera, webkit
            var selection = window.getSelection();
            var range = doc.createRange();
            range.selectNodeContents(text);
            selection.removeAllRanges();
            selection.addRange(range);
        }
    }

    $("body").keydown(function(e) {
        if (e.ctrlKey && (e.keyCode == 65 || e.keyCode == 97)) {
            selectText('copyme');
            e.preventDefault();
        }
    });

});
table, td {
border: solid 1px black;
    margin: 10px;
    padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent iaculis lobortis adipiscing. Donec consequat commodo posuere. Praesent magna orci, suscipit ut facilisis sed, volutpat in lorem. Nulla eleifend.</p>
<table id="copyme">
    <tr><td>A</td><td>B</td><td>C</td></tr>
        <tr><td>D</td><td>E</td><td>F</td></tr>
</table>
<p>Vestibulum ac commodo libero. Aenean vitae magna nulla. Vivamus hendrerit, orci sed pretium aliquam.</p>
mx0
  • 6,445
  • 12
  • 49
  • 54