I have an input, and would like to make have a copy link next to its label.
When I click copy I want to not only copy the input value, but I would like to prepend more texts.
http://www.test.com?code= + input value
How do I do that?
//copy text
function getLink(id) {
var copyText = document.getElementById(id);
copyText.select();
copyText.setSelectionRange(0, 99999); /* For mobile devices */
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
With this code above, only copy the value.
You can edit the value in the current input element, and then restore it to the original value after copied the edited value. Something like this:
function getLink(e) {
const copyPad = e.target.previousElementSibling,
storedValue = copyPad.value,
copyValue = 'http://www.test.com?code=' + storedValue;
copyPad.value = copyValue;
copyPad.select();
copyPad.setSelectionRange(0, 99999); /* For mobile devices */
document.execCommand("copy");
console.log("Copied the text: " + copyPad.value);
copyPad.value = storedValue;
}
const but = document.querySelector('#copyLink');
but.addEventListener('click', getLink);
<input><button id="copyLink">Copy</button>
<input> Paste here to check
A user can't see changes to the input element, because the page is not rendered before all the JS has been executed.
Related
This question already has answers here:
How do I copy to the clipboard in JavaScript?
(27 answers)
Closed 2 years ago.
How do I actually copy some fixed text to clipboard using javascript?
This is my code and it's not working maybe there's another way and I don't know.
<button onclick="Copy()">Copy</button>
<script>
function Copy() {
document.execCommand("copy","Some text here");
}
</script>
I want to copy some fixed text using just button, so I don't have to select texts manually and copy them.
Thanks.
You can try this approach:
<script>
function Copy() {
var copyText = document.createElement("input");
copyText.style="display:none";
copyText.value = "This is a paragraph";
document.body.appendChild(copyText);
copyText.select();
copyText.setSelectionRange(0, 99999); /*For mobile devices*/
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
</script>
try it:
var copy_text_val = document.querySelector('.copy_text');
function Copy() {
copy_text_val.select();
document.execCommand("copy");
console.log(copy_text_val.value);
}
<button onclick="Copy()">Copy</button>
<input type="text" class="copy_text" value="blablabla">
For this action you have to select the text dynamically before actually copying it:
Here is an example:
function copy_text(node){
if(document.body.createTextRange){
const range = document.body.createTextRange();
range.moveToElementText(node);
range.select();
document.execCommand('copy');
}
else if(window.getSelection){
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(node);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
}
else {
console.warn("Could not select text in node");
}
}
// This copy_text function ensures cross-browser compatibility
// What it does is select the text within the range of the node holding the text
// Then executes the "copy" command on that selected text
function clear_selection(){
if(window.getSelection){
window.getSelection().removeAllRanges();
}
else if(document.selection){
document.selection.empty();
}
}
// This clear_selection function clears any selection from the document
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("clipboard-exec").onclick = function(){
copy_text(document.getElementById("clipboard-text"));
// Copy the text on clicking the button
setTimeout(() => { clear_selection() }, 500);
// Clear the selection after 0.5s
}
});
<span id="clipboard-text">This is the text that will be copied to your clipboard when you click on the "Copy" button.</span>
<button><span id="clipboard-exec"><i class="fa fa-copy"> Copy</i></span></button>
Of course with this function you can just restructure it to fit your needs.
Also note that what you are trying to accomplish by copying directly to the keyboard without a valid text node actually holding the text won't work, I guess for security purposes
But you can create a node in the document with the text but hide it from view then select it using this function .. NOTE the text you are copying to the clipboard has to be actually in the document, for you to execute the "copy" command on it
I want to make a bookmarklet to save a string parsed from an Array and I'm looking for an easy way to save my const cp = 'text' into clipboard. Is there any solution for this problem? Thanks in advance :)
Have a look around before posting. This is from the w3schools site. Lots of great explanations there. https://www.w3schools.com/howto/howto_js_copy_clipboard.asp
function myFunction() {
/* Get the text field */
var copyText = document.getElementById("myInput");
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0, 99999); /*For mobile devices*/
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied the text: " + copyText.value);
}
I have used the following function to achieve this.
const copyToClipboard = (e) => {
const el = document.createElement('input')
el.value = window.location // I need a string that was located in the url => you should use whatever value you need, and set the input value to that, obviously.
el.id = 'url'
el.style.position = 'fixed'
el.style.left = '-1000px' // otherwise, sometimes, it creates an input element visible on the screen
el.setAttribute('readonly', true) // to prevent mobile keyboard from popping up
document.body.appendChild(el)
el.select()
document.execCommand('copy')
}
You can create a function like this using copy event
const copyToClipboard = (text) => {
document.addEventListener('copy', function(e) {
e.clipboardData.setData('text/plain', text);
e.preventDefault();
});
document.execCommand('copy');
}
This answer is also helpful.
I've got a formula that calculates a value. This value I want to insert to an Excel sheet. To make it comfortable to the user I want to put it to the clipboard automatically.
I try to do my first steps in JS and encountered this (probably) very simple problem. But all methods I found are related to raw values of html input-tags. I never have seen any copy-to-clipboard functions from values created in js.
var EEFactor = 1*1; // just a formula to calculate a value
copyValue2Clipboard(EEFactor);
function value2Clipboard(value) {
// please help
}
There is an example with a great explanation here
Try like this.
function copyToClipboard(str) {
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);
};
var EEFactor = 1*1;
copyToClipboard(EEFactor);
const copyToClipboard = str => {
const el = document.createElement('textarea'); // Create a <textarea> element
el.value = str; // Set its value to the string that you want copied
el.setAttribute('readonly', ''); // Make it readonly to be tamper-proof
el.style.position = 'absolute';
el.style.left = '-9999px'; // Move outside the screen to make it invisible
document.body.appendChild(el); // Append the <textarea> element to the HTML document
const selected =
document.getSelection().rangeCount > 0 // Check if there is any content selected previously
? document.getSelection().getRangeAt(0) // Store selection if found
: false; // Mark as false to know no selection existed before
el.select(); // Select the <textarea> content
document.execCommand('copy'); // Copy - only works as a result of a user action (e.g. click events)
document.body.removeChild(el); // Remove the <textarea> element
if (selected) { // If a selection existed before copying
document.getSelection().removeAllRanges(); // Unselect everything on the HTML document
document.getSelection().addRange(selected); // Restore the original selection
}
};
What I want - A button that (onclick) adds the selected text to a textbox (with the name of "body"). I would like it to be prefixed with a linebreak and greater than sign, and at the end two linebreaks/a paragraph.
My current code:
function
addtext() {
var newtext = '\uA' '\u3E' document.getSelection() '\uA';
this.email.comments.value += newtext;
location.href="#emailme"}
Basically, after selecting text and clicking the button, add the selected text to the form with a few changes. What actually happens is absolutely nothing.
Notes: NO JQUERY. JQuery answers will be ignored. Pure JS only.
try this
var textBox = document.getElementById("text-box"); // replace the id by your text box identifier
var addTextButton = document.getElementById("add-text-button"); // replace the id by your button identifier
function addText() {
// \u000a is escape sequence for line feed
var newText = '\u000a>' + document.getSelection().anchorNode.textContent + '\u000a\u000a';
// add any extra data to new text here like newText += extraData
textBox.value += newText;
}
addTextButton.addEventListener("click", function(event) {
event.preventDefault();
addText();
});
I'm using javascript and jQuery to design a comment box.
My page has a textarea and 3 buttons (bold, underline and italic). If a user types text in the textarea, selects and clicks any button, the selected text should become bold, underlined or italicised (I have this functionality below).
My problem is that after clicking a button with text selected, although the html tags are correctly inserted, the selection is lost. That is, when I type: "Hello, I'm here.", select "I'm here" and click the bold button. I'm here becomes bold but if I want to also underline or italicise, I have to reselect the text.
So, my question is: How do I re-select the selected text in the textarea?
I tried myTextarea.select() but this code will select the entire contents of the textarea, not only the selected text.
Update:
Here is what I've got so far:
var mystring = ""; // default string
/* Bold event */
function Bold()
{
var startString;
var endString;
var startPos; // starting position
var endPos; // ending position
var selectedText;
var temp = document.getElementById("myTextarea");
// check if text is selected
if(temp.selectionStart !== undefined)
{
startPos = temp.selectionStart;
endPos = temp.selectionEnd;
selectedText = temp.value.substring(startPos, endPos);
startString = temp.value.substring(0, startPos);
endString = temp.value.substring(endPos, temp.value.length);
}
$("#myTextarea").val(startString + "[B]" + selectedText + "[/B]" + endString); // rewrite textarea value
if(mystring !== "") // check if default string is NOT null, return null if it's the first clicked
{
mystring = mystring.replace(selectedText, "<b>" + selectedText + "</b>");
}
else
{
mystring = startString + "<b>" + selectedText + "</b>" + endString;
}
// write to preview panel
$("#preview").html(mystring);
$("#myTextarea").focus();
}
When I select "I'm here" in the textarea and click the bold button the code above will insert [B] and [/B] into the textarea and <b> tags into the preview panel.
To reselect the text you can do:
temp.setSelectionRange(startPos, endPos + 6);
I've added + 6 because you're inserting 6 new characters so I'm expanding the selection to include them. You could also add 3 to startPos and endPos (and let the characters wrap the selection) - IMO this is inferior UX wise.