Copy password input field content in Vue to clipboard

I'm currently working on a Vue app that includes a form input for creating passwords. I've managed to implement a button that shows/hides the password, but I'm struggling with adding a copy to clipboard function. It doesn't seem to be working as expected. Can you help me identify what I'm doing wrong?

Code snippet

<small class="font-wieght-bold text-success mb-0" v-if="isCopied">Copied</small>
      
<div class="input-group">
  <input :type="showPassword ? 'text' : 'password'" class="form-control" ref="password" required v-model="password">
  <div class="input-group-append">
    <button class="btn btn-secondary" @click.prevent="copyToClipboard()"><i class="fas fa-clipboard"></i></button>
  </div>
</div>

Vuex code part

viewPassword() {
  this.showPassword = !this.showPassword;
},
copyToClipboard() {
  this.$refs.password.select();
  document.execCommand('copy');
  this.isCopied = true;
  setTimeout( () => { this.isCopied = !this.isCopied },3000);
}

Answer №1

To effectively copy the contents of your v-model, focus on extracting the data rather than duplicating the input itself.

A useful approach is to implement a function that facilitates copying from a variable.

This function creates a new text box, utilizes the copy command, and promptly removes it within a single event loop to prevent rendering.

const copyTextToClipboard = (text) => {
  const textArea = document.createElement('textarea')

  // Styling added for necessary functionality and minimal visual impact

  textArea.style.position = 'fixed'
  textArea.style.top = '0'
  textArea.style.left = '0'

  textArea.style.width = '2em'
  textArea.style.height = '2em'

  textArea.style.padding = 0

  textArea.style.border = 'none'
  textArea.style.outline = 'none'
  textArea.style.boxShadow = 'none'

  textArea.style.background = 'transparent'

  textArea.value = text

  document.body.appendChild(textArea)

  textArea.select()

  try {
    const successful = document.execCommand('copy')
    const msg = successful ? 'successful' : 'unsuccessful'
    console.log('Copying text command was ' + msg)
  } catch (err) {
    console.log('Oops, unable to copy')
  }

  document.body.removeChild(textArea)
}

Answer №2

After exploring different options, I discovered a new approach using the clipboard API as an alternative solution to the accepted answer. By utilizing the clipboard.writeText() method, I was able to efficiently copy the v-modeled data directly into the clipboard, even when dealing with

<input type="password">
. Below is the improved version of the copyToClipboard() method:

    copyToClipboard() {
      navigator.clipboard.writeText(this.password);
      this.isCopied = true;
      setTimeout( () => { this.isCopied = !this.isCopied },3000);
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extract the content of a textbox within an iframe located in the parent window

Is it possible to retrieve the value of a text box in an iframe from the parent page upon clicking a button? Below is an example code snippet showcasing the situation: <div> <iframe src="test.html" > <input type=text id="parent_text"> & ...

Tips for sending a Postgres Pool or Client over a socket

After deploying my server to Heroku, I encountered an issue with sending a request to my Raspberry Pi for running a scraping function and updating a table in the Heroku Postgres database. The problem seems to be related to the client.query() function not b ...

The function react__WEBPACK_IMPORTED_MODULE_0___default.a.useContext is not recognized when implementing Autocomplete within Material UI

Every time I attempt to create an Autocomplete tag utilizing Material UI, an error pops up, which can be seen in the following link: https://i.sstatic.net/kxKR4.png The Autocomplete code snippet is as follows: import React, {useState, useEffect, useCo ...

Show a virtual numeric keypad on the HTML input fields when they are set as type text specifically for mobile devices in a unique situation

When accessing the following web page from a mobile device, I currently have number input fields with comma separators added. However, in order to implement the comma separation function, I had to set the input type to text. This resulted in showing an alp ...

Can I use unclosed tags with v-for for iteration in Vue.js?

Imagine I am working on a project with Vue.js and here is some of my vue-code: <template> <div v-for="(item, index) in items"> <div v-if="item.isComponent"> <component :is="item.value"/> </div> ...

How can I disable auto-fill for password input fields? Setting autocomplete="off" doesn't seem to be working

Hey there, I'm having some trouble with the autocomplete feature in Google Chrome. Can anyone suggest an alternative way to disable autocomplete for password fields? By the way, my project is using Vue.js. ...

Vue: Clear the current form selection with a button click

<b-row class="mb-3"> <b-col> <div class="float-right"> <b-form-select v-model="selected" :options="options" ></b-form-select> ...

What could be causing the removeChild() method to fail when trying to delete a list item in JavaScript DOM manipulation?

Check out this interactive shopping list. You can add items, delete them, and mark them as completed. Adding and deleting items works fine, but there's an issue when toggling them. Issue (occurs when toggling multiple list items) If you add 3 items ...

Exploring the differences between utilizing request.body in building RESTful APIs with Django versus Node.js

As I dive into learning the Django framework, my main aim is to leverage this knowledge in creating a rest api. Although I've looked into using django-rest framework, my current job necessitates a focus on Django specifically. In my journey so far, I ...

What steps can be taken to fix a syntax error in a NodeJS express server code?

I am currently facing a syntax error in the code below, and I'm struggling to fix it. The specific error message is as follows: node staticapi.js /Users/v/Desktop/CS-Extra/EIP/A5/staticapi.js:123 res.status(200).send("Api is running") ...

Breaking down objects or arrays to extract specific values in React components

Some articles recommend using ES6 destructuring for React props & state as a best practice. For example: const { showModal, hideModal } = this.props; While I understand the benefits of cleaner code, I recently discussed with another developer who suggest ...

Acquiring the specific checkbox value using JQuery

I am encountering an issue with my JQuery function that is supposed to print out the unique value assigned to each checkbox when clicked. Instead of displaying the correct values, it only prints out '1'. Each checkbox is assigned an item.id based ...

Maintain the initial value using ko.mapping.fromJS

How can I prevent new data fetched from an AJAX call using ko.mapping.fromJS from replacing the existing data in my observableArray? I want to append the new data without losing the previous entries. function ViewModel() { var self = this; self. ...

Changing Vue Model Arrays

In my Vue template, I am working with an object that contains two arrays: one for dummy or placeholder values and another for actual data. data() { var tableColumns = new Array(); tableColumns.push({"dummyValues": ["date 1", "date 2"], "csvValues": [] ...

Accessing XML files locally via JavaScript on Chrome or Internet Explorer, with compatiblity for Android mobile devices as well

Looking to extract and display data from an XML file directly in an HTML page without the need for a web server. Ready to dive into using JavaScript, jQuery, or Ajax to get the job done. ...

I'm currently attempting to determine the total cost of a series of operations, however, I am not receiving any results

Here is the code snippet from my HTML file: <tr> <td><input id="z1" type="number" oninput="calculateSubTotal()"> </td> <td>Shirts - WASH - Qty 1 to 4</td> <td>2.50 ea</td> ...

Differences between applying addClass(undefined) and addClass(null)

At times, it crosses my mind to include a class in a chain, depending on certain conditions. What would be the most fitting semantic value to add no class? For instance: $(".element").performAction().addClass(condition ? "special-class" : undefined).perf ...

Enhancing Chart Accessibility with Highcharts in VUE.js

We have a client requesting full-screen readability and keyboard navigation for their website (which is hosted on Squarespace and we created a Vue plugin for them). I have successfully implemented these features in all areas of their site, including Leafl ...

What is the proper way to incorporate a URL query into a path within the Vue.js router?

Template Component.vue utilizes the route in this manner: <router-link :to="{ name: 'club' }"> <lazy-image src="club.jpg" class="club_class" alt="Club alt" /> </router-link> ...

Issue with importing a file using JQuery causing the click event to not function properly

I have a file named navigation.html located in a directory called IMPORTS <!-- Navigation --> <div class="navbar-inner"> <div class="container"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-ta ...