Projects

Create Messenger Pop Up ChatBox Type Writer ChatGpt Basic Copy Text Using Tolltip Digital Clock CountDown Timer Create StopWatch FB login from Tab Button Accordion Auto Image Gallery DropDown Menu Modal Box Modal Image Box Scroll Indicator To Do List Autocomplete Remember Search History Toggle Switch Calender Layout Dynamic Calender Alarm Set Password Validation Password Generator Age Calculator Multi Step Form Weather API

Copying a Text From Input Field ©️

Note: If you are a beginner, this is something you need to know. Scroll the below section or Click here
  • HTML Input field
  • Clipboard API() mehtod in JS
  • document.execCommand('copy')
  • select() method in JS
  • You need information about JS function and HTML buttons

Write something in the input field and then click the button to copy the text.

After Clicked the button then paste it into NotePad or anywhere else for testing.

HTML


<input type="text" id="copy" placeholder="write something...">
<button onclick="copyText()">Copy</button>

JavaScript



function copyText() {
let inputvalue = document.getElementById("copy");
inputvalue.select(); // select method can only use html element, not available on strings or plain values.
console.log(inputvalue);
navigator.clipboard.writeText(inputvalue.value);
}

You Can Use Alternative JavaScript document.execCommand('copy') Method.



const inputvalue=document.querySelector("#copy");
inputvalue.select();
inputvalue.setSelectionRange(0,99999);

try{
    if(document.execCommand('copy')){
        alert("Text is copied")
    }
    else{
        alert("Failed to copy");
    }
}
catch(err){
    console.log("Failed "+err);

}

window.getSelection().removeAllRanges();
   


HTML Input field

  • Input fields in HTML use to gather data from user such as text, numbers, dates and more.
    Example: <input type="text">

navigator.clipboard.writeText(param..)

  • Purpse: Enables copying text to the clipboard programmatically.

select() method

  • Here select method select input element .and the select() method is not available on strings or plain values.
    Example: const inputElement = document.getElementById('copy');
    inputElement.select()

document.execCommand('copy')

  • This method copies the currently selected text or content within the editable element (like input or textarea) to the clipboard.

window.getSelection().removeAllRanges

  • Clear all current selection whithin the document, ensuring no text or content remains selected after this operation.