I have a select control with pre defined values and I want my users to be able to copy the selected item\'s text with CTRL + C
I don\'t want them to be able to chang
Fiddle
As opposed to @Dogoku's answer, this is more direct, you don't need to first select your text. Just hit ctrl+c whilst the has focus and it will copy the selected
's text to your clipboard.
This'll work in modern browsers (including IE>7) without jQuery or funky css.
//to be ran on keydown, which occurs before clipboard copy
function copyWatch(e) {
e = e || event;
if (
//not ctrl+C
(!(e.ctrlKey && e.keyCode == '67')) ||
//nothing selected
(this.selectedIndex < 0)
)
return;
//create selectable text
var copyEl = document.createElement('textarea');
copyEl.innerHTML = this.options[this.selectedIndex].innerHTML;
//hide it, but in a way the browser thinks is clickable
//(no visibility:hidden, display:none)
copyEl.style.position = 'absolute';
copyEl.style.left = '-9999px';
var that = this;
//add a call back for after the ctrl+c is completed
copyEl.onkeyup = function() {
//remove the extraneous element
copyEl.parentNode.removeChild(copyEl);
//return focus to the select
that.focus();
};
//add it to the document, and highlight all the text in the textarea,
//ready for the ctrl+c copy event to fire
document.body.appendChild(copyEl).select();
}