Can we select all table td by pressing CTRL+A button using jQuery or javascript?
Asked
Active
Viewed 1,345 times
1
-
what do you understand by "selecting" the td ? Add some visual effects for the user or select it in jquery ? – mas-designs Mar 13 '12 at 13:43
2 Answers
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
-
but it selects all the text on the page also. This should not happen – manishjangir Mar 13 '12 at 13:52
-
That's why I said you are gonna have to do it programmatically. – Daniel Ribeiro Mar 13 '12 at 13:54
-
1I think the question gets at a useful notion, but it's unclear (especially the ambiguity between JQuery selection and browser selection). – Chet Mar 13 '12 at 13:54
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