How to copy a variable into the clipboard - javascript

How do I copy a variable into the clipboard?
It always return:
Uncaught TypeError: copyText.select is not a function
Code
function copy() {
var allDesCode2 = document.getElementsByClassName("desCode2");
var copyText = "ABC";
for(var i=0; i<allDesCode2.length; i++) {
copyText += allDesCode2[i].innerHTML;
}
copyText.select();
document.execCommand("copy");
}

The copy() function below can help to copy a string from a variable. You can use this method in pure JavaScript without the help of any libraries, such as jQuery.
function copy() {
var copyText = "Hooray ! I will be copied";
var el = document.createElement('textarea');
el.value = copyText;
el.setAttribute('readonly', '');
el.style = {
position: 'absolute',
left: '-9999px'
};
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
<button onclick="copy()">Copy</button>

I assume you were using this article as a reference. But in this example .select() was used on <input> element, and you're trying to execute this method on a variable.
You can look at this question (your question is a possible duplicate of this). It has a plenty of useful answers which will help you.

You just try to select text without any input. That's mistake one. Also I just read the copy event must be inside the click event (maybe there are more events to copy - reference).
I attached the copy function on your div, put its HTML content into the input, and then copy it.
function copy() {
var allDesCode2 = document.getElementsByClassName("desCode2");
var copyText = "ABC";
for (var i = 0; i < allDesCode2.length; i++) {
copyText += allDesCode2[i].innerHTML;
}
$('input').val(copyText).select();
document.execCommand('copy');
}
$('.desCode2').on('click', copy);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="desCode2">123123123123</div>
<input>

Related

How to save Clipboard.js value to string

I started using clipboards.js to copy the content of a div with the click of the button but now I need to save it to a string so I can delete new lines to be shown like 1 paragraph but I cannot access to data that is stored to clipboard
this function here is to save to clipboard using clipboard.js and you can see I was trying to save it to "var str2" but it shows this "Cannot read property '_target' of undefined"
_this.testClick = function () {
var clipboard = new Clipboard('.clipboard');
var str2 = clipboard.clipboardAction._target.innerText.replace(/\n|\r/g, "");
_this.copyStringToClipboard(str2);
};
and this is the function that copies again but without spaces
_this.copyStringToClipboard = function (str) {
// Create new element
var el = document.createElement('textarea');
// Set value (string to be copied)
el.value = str;
// Set non-editable to avoid focus and move outside of view
el.setAttribute('readonly', '');
el.style = {
position: 'absolute',
left: '-9999px'
};
document.body.appendChild(el);
// Select text inside element
el.select();
// Copy text to clipboard
document.execCommand('copy');
// Remove temporary element
document.body.removeChild(el);
}
how can I access to inner text or clipboard so I can save it to str2?
Try using ClipboardJS() and success event
var clipboard = new ClipboardJS('.clipboard');
clipboard.on('success', function(e) {
console.log(e.text);
console.log(e.text.replace(/\n|\r/g, ""));
});
<script src="https://cdn.jsdelivr.net/npm/clipboard#2/dist/clipboard.min.js"></script>
<button class="clipboard" data-clipboard-text="Just
because
you can
doesn't mean you should — clipboard.js">
Copy
</button>

Copy output of a JavaScript variable to the clipboard

I have no knowledge of JavaScript, but I managed to put this code together using bits and bolts from various Stack Overflow answers. It works OK, and it outputs an array of all selected checkboxes in a document via an alert box.
function getSelectedCheckboxes(chkboxName) {
var checkbx = [];
var chkboxes = document.getElementsByName(chkboxName);
var nr_chkboxes = chkboxes.length;
for(var i=0; i<nr_chkboxes; i++) {
if(chkboxes[i].type == 'checkbox' && chkboxes[i].checked == true) checkbx.push(chkboxes[i].value);
}
return checkbx;
}
And to call it I use:
<button id="btn_test" type="button" >Check</button>
<script>
document.getElementById('btn_test').onclick = function() {
var checkedBoxes = getSelectedCheckboxes("my_id");
alert(checkedBoxes);
}
</script>
Now I would like to modify it so when I click the btn_test button the output array checkbx is copied to the clipboard. I tried adding:
checkbx = document.execCommand("copy");
or
checkbx.execCommand("copy");
at the end of the function and then calling it like:
<button id="btn_test" type="button" onclick="getSelectedCheckboxes('my_id')">Check</button>
But it does not work. No data is copied to clipboard.
function copyToClipboard(text) {
var dummy = document.createElement("textarea");
// to avoid breaking orgain page when copying more words
// cant copy when adding below this code
// dummy.style.display = 'none'
document.body.appendChild(dummy);
//Be careful if you use texarea. setAttribute('value', value), which works with "input" does not work with "textarea". – Eduard
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
copyToClipboard('hello world')
copyToClipboard('hello\nworld')
OK, I found some time and followed the suggestion by Teemu and I was able to get exactly what I wanted.
So here is the final code for anyone that might be interested. For clarification, this code gets all checked checkboxes of a certain ID, outputs them in an array, named here checkbx, and then copies their unique name to the clipboard.
JavaScript function:
function getSelectedCheckboxes(chkboxName) {
var checkbx = [];
var chkboxes = document.getElementsByName(chkboxName);
var nr_chkboxes = chkboxes.length;
for(var i=0; i<nr_chkboxes; i++) {
if(chkboxes[i].type == 'checkbox' && chkboxes[i].checked == true) checkbx.push(chkboxes[i].value);
}
checkbx.toString();
// Create a dummy input to copy the string array inside it
var dummy = document.createElement("input");
// Add it to the document
document.body.appendChild(dummy);
// Set its ID
dummy.setAttribute("id", "dummy_id");
// Output the array into it
document.getElementById("dummy_id").value=checkbx;
// Select it
dummy.select();
// Copy its contents
document.execCommand("copy");
// Remove it as its not needed anymore
document.body.removeChild(dummy);
}
And its HTML call:
<button id="btn_test" type="button" onclick="getSelectedCheckboxes('ID_of_chkbxs_selected')">Copy</button>
For general purposes of copying any text to the clipboard, I wrote the following function:
function textToClipboard (text) {
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
The value of the parameter is inserted into value of a newly created <textarea>, which is then selected, its value is copied to the clipboard and then it gets removed from the document.
Very useful. I modified it to copy a JavaScript variable value to clipboard:
function copyToClipboard(val){
var dummy = document.createElement("input");
dummy.style.display = 'none';
document.body.appendChild(dummy);
dummy.setAttribute("id", "dummy_id");
document.getElementById("dummy_id").value=val;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
When you need to copy a variable to the clipboard in the Chrome dev console, you can simply use the copy() command.
https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#copyobject
I managed to copy text to the clipboard (without showing any text boxes) by adding a hidden input element to body, i.e.:
function copy(txt){
var cb = document.getElementById("cb");
cb.value = txt;
cb.style.display='block';
cb.select();
document.execCommand('copy');
cb.style.display='none';
}
<button onclick="copy('Hello Clipboard!')"> copy </button>
<input id="cb" type="text" hidden>
Use Clipboard API
text = "HEllo World";
navigator.clipboard.writeText(text)
It works on Chrome 66+, Edge 79+, Firefox 63+ & doesn't work on I.E.
Read More About Clipboard API At MDN Docs
Nowadays there is a new(ish) API to do this directly. It works on modern browsers and on HTTPS (and localhost) only. Not supported by IE11.
IE11 has its own API.
And the workaround in the accepted answer can be used for unsecure hosts.
function copyToClipboard (text) {
if (navigator.clipboard) { // default: modern asynchronous API
return navigator.clipboard.writeText(text);
} else if (window.clipboardData && window.clipboardData.setData) { // for IE11
window.clipboardData.setData('Text', text);
return Promise.resolve();
} else {
// workaround: create dummy input
const input = h('input', { type: 'text' });
input.value = text;
document.body.append(input);
input.focus();
input.select();
document.execCommand('copy');
input.remove();
return Promise.resolve();
}
}
Note: it uses Hyperscript to create the input element (but should be easy to adapt)
There is no need to make the input invisible, as it is added and removed so fast. Also when hidden (even using some clever method) some browsers will detect it and prevent the copy operation.
At the time of writing, setting display:none on the element didn't work for me. Setting the element's width and height to 0 did not work either. So the element has to be at least 1px in width for this to work.
The following example worked in Chrome and Firefox:
const str = 'Copy me';
const el = document.createElement("input");
// Does not work:
// dummy.style.display = "none";
el.style.height = '0px';
// Does not work:
// el.style.width = '0px';
el.style.width = '1px';
document.body.appendChild(el);
el.value = str;
el.select();
document.execCommand("copy");
document.body.removeChild(el);
I'd like to add that I can see why the browsers are trying to prevent this hackish approach. It's better to openly show the content you are going copy into the user's browser. But sometimes there are design requirements, we can't change.
I just want to add, if someone wants to copy two different inputs to clipboard. I also used the technique of putting it to a variable then put the text of the variable from the two inputs into a text area.
Note: the code below is from a user asking how to copy multiple user inputs into clipboard. I just fixed it to work correctly. So expect some old style like the use of var instead of let or const. I also recommend to use addEventListener for the button.
function doCopy() {
try{
var unique = document.querySelectorAll('.unique');
var msg ="";
unique.forEach(function (unique) {
msg+=unique.value;
});
var temp =document.createElement("textarea");
var tempMsg = document.createTextNode(msg);
temp.appendChild(tempMsg);
document.body.appendChild(temp);
temp.select();
document.execCommand("copy");
document.body.removeChild(temp);
console.log("Success!")
}
catch(err) {
console.log("There was an error copying");
}
}
<input type="text" class="unique" size="9" value="SESA / D-ID:" readonly/>
<input type="text" class="unique" size="18" value="">
<button id="copybtn" onclick="doCopy()"> Copy to clipboard </button>
function CopyText(toCopy, message) {
var body = $(window.document.body);
var textarea = $('<textarea/>');
textarea.css({
position: 'fixed',
opacity: '0'
});
textarea.val(toCopy);
body.append(textarea);
textarea[0].select();
try {
var successful = document.execCommand('copy');
if (!successful)
throw successful;
else
alert(message);
} catch (err) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", toCopy);
}
textarea.remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<button type="button" onClick="CopyText('Hello World', 'Text copped!!')">Copy</button>

Uncaught ReferenceError in jQuery

When I click the button to insert bbcode to textarea The console alert : "Uncaught ReferenceError: myTextarea is not defined". Can you help me solve this problem ?
I have a code:
$(function(){
function formatText(el,tagstart,tagend){
var selectedText=document.selection?document.selection.createRange().text:el.value.substring(el.selectionStart,el.selectionEnd);// IE:Moz
var newText='['+tagstart+']'+selectedText+'[/'+tagend+']';
if(document.selection){//IE
el.focus();
var st=getCaret(el)+tagstart.length+2;
document.selection.createRange().text=newText;
var range=el.createTextRange();
range.collapse(true);
range.moveStart('character', st);
range.moveEnd('character',selectedText.length);
range.select();
el.focus();
}
else{//Moz
var st=el.selectionStart+tagstart.length+2;
var end=el.selectionEnd+tagstart.length+2;
el.value=el.value.substring(0,el.selectionStart)+newText+el.value.substring(el.selectionEnd,el.value.length);
el.focus();
el.setSelectionRange(st,end)
}
}
function getCaret(el) { // IE mission is tricky :)
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
var add_newlines = 0;
for (var i=0; i<rc.text.length; i++) {
if (rc.text.substr(i, 2) == '\r\n') {
add_newlines += 2;
i++;
}
}
return rc.text.length + add_newlines;
}
$("elements").after('<form action="/post" method="post" name="myForm"><textarea placeholder="Comments..." name="myTextarea"></textarea><span class = "repbbcode" title = "Bold" value="b" style="font-weight:bold" >B</span></form>');
$(".repbbcode").on("click" , function(){
formatText(myTextarea,'b','b');
});
});
$(".repbbcode").on("click" , function(){
formatText(myTextarea,'b','b');
^^^^^^^^^^
});
myTextarea is not defined. There is no
var myTextarea = ....
in your code. You need something like
$(".repbbcode").on("click" , function(){
var myTextarea = $("[name='myTextarea']).get(0);
formatText(myTextarea,'b','b');
});
You need to add var myTextarea = document.getElementsByName('myTextarea')[0];
$(".repbbcode").on("click" , function(){
var myTextarea = document.getElementsByName('myTextarea')[0]; // added myTextarea
formatText(myTextarea,'b','b');
});
In this line of code:
formatText(myTextarea,'b','b');
You have to pass as the first argument a DOM element. You can't just pass the name of a DOM element. It's easiest to use document.getElementById("myTextArea") and then set id="myTextArea" in your element.
So, your textarea HTML would be <textarea id="myTextArea" ...>.
And, your code would be:
var textareaElement = document.getElementById("myTextArea");
formatText(textareaElement,'b','b');
If you want to get the DOM element by name, you can do that too:
var textareaElement = document.getElementsByName("myTextArea")[0];
formatText(textareaElement,'b','b');
What is different here is that document.getElementsByName() returns a list of potentially multiple elements so you have to reach into that list with [0] to get the first item in the list to pass to your function.
There are many different ways to do this (using name, class, id, etc...). Usually if you are trying to get one unique element in a page, you would give it an id and use document.getElementById() or the jQuery equivalent.

get dynamic text in text area on every click on div

I want to open the CKEDITOR on click-event of div, and want the div contents in that textarea of ckeditor
but somehow this is not working.
Thanks in advance, and sorry for my poor english
function createEditor() {
$('DIV').click(function(event) {
var id1 = event.target.id;
//alert(id1);
document.getElementById("editor1").value = '';
var newtext = document.getElementById(id1).innerHTML;
alert(newtext);
document.getElementById("editor1").value += newtext;
});
document.getElementById("contents").style.display = "block";
}
Remove createEditor() function and try it
$('DIV').click(function(event) {
var id1 = event.target.id;
//alert(id1);
document.getElementById("editor1").value = '';
var newtext = document.getElementById(id1).innerHTML;
alert(newtext);
document.getElementById("editor1").value += newtext;
});
document.getElementById("contents").style.display = "block";
Try this to add data to the textarea.
$("#editor1").val(newtext);
or use
$('#editor1').append(newtext);
This solution will rely more on jQuery. First, if you want this function to be triggered when ever a div is clicked, get rid of your function(), it's not necessary since your event will be triggered every time a div is clicked.
This should solve your problems:
$('div').click(function(e) {
$id1 = $(this).attr("id");
alert($id1);
$("#editor1").val(' '); //Are you sure you want to empty your textarea?
$newtext = $("#"+$id1).html();
alert($newtext);
$("#editor1").val($newtext); //Because when you append the newtext it won't append but replace the text it's already on this.
$("#contents").css("display","block");
});
Here's a fiddle with a similar example of using your function:
If you just want the text of the clicked div and you're using jQuery try
$("div").click( function() {
var newtext = $(this).text();
$("#editor1").text( newtext );
});

How can I make text bold with nodes and .createElement("b")?

I have to make text bold if I click on a button using nodes and createElement but I don't really know how...
html (This is the text I want to make bold):
<p id="textalt">Dies ist ein Text in einem P-Tag</p>
javascript:
function fettmachen(){
var neuB = document.createElement("b");
document.getElementById("textneu").insertBefore(neuB, document.getElementById("textneu").nextSibling);
}
I don't know how it works.
"I have to do it with nodes and createElement"
function fettmachen(){
// create the "b" element
var neuB = document.createElement("b");
// fetch the "textneu" element by ID
var textneu = document.getElementById("textneu");
// append the firstChild of "nextneu" to the "neuB"
neuB.appendChild(textneu.firstChild);
// append the "neuB" to the "nextneu"
nextneu.appendChild(neuB);
}
I suggest, instead of adding new tags, just use CSS, and add a class to the element.
CSS:
.boldText{
font-weight: bold;
}
JavaScript:
function fettmachen(){
document.getElementById("textalt").className += ' boldText';
}
I'd just put a style on the <p> tag on the button press. Maybe something like...
function fettmachen(){
var neuB = document.getElementById("textalt");
neuB.style.fontWeight = "bold";
}
Well, you could use the following code. It's longer and could be condensed - I find it clearer to read, personally.
function fettmachen()
{
var pElem = document.getElementById('textAlt');
var text = pElem.innerHTML;
var bElem = document.createElement('b');
bElem.innerHTML = text;
pElem.innerHTML = '';
pElem.appendChild(bElem);
}
This is how you make the text bold
function fettmachen(){
var p = document.getElementById("textneu");
p.style.fontWeight = "bold;"
}
If you have to use js for some reason for instance you need to only bold certain words maybe, and don't have access to the style sheet here you go. Otherwise use what Rocket has suggested.
Seriously only use a solution like this if at some point you will need to only bold certain words, or groups of words within an element.
function fettmachen(){
var neuB = document.createElement("b"),
textEl = document.getElementById("textalt"),
text = textEl.textContent;
neuB.textContent = text;
textEl.textContent = "";
textEl.appendChild(neuB);
}
Live Demo
And to unbold.
function unbold(){
var textEl = document.getElementById("textalt"),
boldEls = textEl.getElementsByTagName("b"),
text = "";
for(var i = 0; i < boldEls.length; i++){
text+=boldEls[i].textContent;
textEl.removeChild(boldEls[i]);
}
textEl.textContent = text;
}
Live Demo 2

Categories