Objective: to copy text in a bootstrap modal to the clipboard.
JS:
$(document).ready(function(){
$(document).on('click','#copy-btn', function(){
// var value = $('#error-message').html();
// using a static value, just to eliminate any question
// about what should be copied.
copytext('kilroy tested this');
})
});
function copytext(text) {
var textField = document.createElement('textarea');
textField.innerText = text;
document.body.appendChild(textField);
textField.select();
document.execCommand('copy');
textField.remove();
console.log('should have copied ' + text); // but it refuses to do so when a modal is used!
}
This Works:
When I try this without a bootstrap modal popup, kilroy tested this
is copied to my clipboard:
<button type="button" class="btn btn-success" id="copy-btn">Copy</button>
This Doesn't:
But... when I move the <button>
into the modal, nothing gets copied to the clipboard, even though the console reports "should have copied kilroy tested this
".
<!-- AJAX Error Popup -->
<div class="modal fade" id="ajax-error" tabindex="-1" role="dialog" aria-labelledby="errorModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header modal-header-danger">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="errorModal">Error Detected!</h4>
</div>
<div class="modal-body" id="error-message"><!-- AJAX message inserted here --></div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="copy-btn">Copy</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I'm at a loss for any other way to troubleshoot this--
- I've demonstrated that the
copytext()
function works, - I've eliminated any question about the source of what should be copied, and
- I've demonstrated that
copy-btn
is being called when the button is clicked (copytext()
is being called and logging to the console).
The only thing left is some wonkiness about the bootstrap modal.
Using jquery 2.1.1 and bootstrap 3.3.6
Open to any ideas or workarounds :)