Removing all text inside an input field with Vue

I am trying to create a password input field using type 'text' instead of 'password.'

<input type="text" v-model="form.password" @input="test" />
<input type="hidden" v-model="form.hiddenPassword" />

As part of my approach, I have implemented some methods. When I enter 'a', it gets replaced by * and 'a' goes into hiddenPassword.

   test(e) {
      if (e.inputType === "deleteContentBackward") {
        this.form.hiddenPassword = this.form.hiddenPassword.substr(
          0,
          this.form.hiddenPassword.length - 1
        );
        this.form.password = this.masking(this.form.hiddenPassword);
        console.log(this.form.hiddenPassword);
      } else {
        this.form.hiddenPassword =
          this.form.hiddenPassword +
          this.form.password.substr(this.form.password.length - 1);
        this.form.password = this.masking(this.form.hiddenPassword);
      }
    },
    masking(input) {
      const lng = input.length;
      let maskingResult = "";
      maskingResult += "*".repeat(lng);
      return maskingResult;
    }

While this method works effectively for regular usage, it has a specific issue when attempting to delete the entire password in the input field using Ctrl+A and Backspace, as it only deletes one character at a time.

I am seeking guidance on how to detect Ctrl+A or select a range with the mouse to delete the entire password. Any solutions or suggestions would be greatly appreciated. Thank you for taking the time to read this.

Answer №1

To ensure your code functions correctly, it should be noted that modifications can be made to the string regardless of whether text is added or removed from the beginning or end. This method allows for changes in the middle of the string as well by utilizing the selectionStart property to track alterations.

Furthermore, this code effectively handles the use of the Delete key. The process involves comparing the lengths of form.hiddenPassword and form.password instead of monitoring event types.

The masking functionality relies on the standard replace method, eliminating the need for a custom approach.

...
  data: {
    form: {
      hiddenPassword: '',
      password: ''
    }
  },
  methods: {
    test: function (e) {
      let caretPosition = e.target.selectionStart
      let restPartLength = this.form.password.length - e.target.selectionStart
      if (this.form.hiddenPassword.length > this.form.password.length) {
        this.form.hiddenPassword = this.form.hiddenPassword.substr(0, caretPosition) +                   
          this.form.hiddenPassword.substring(
            this.form.hiddenPassword.length-restPartLength, 
            this.form.hiddenPassword.length);
      } else {
        let inserted = this.form.password.replace(/\*/g,'');
        this.form.hiddenPassword =
          this.form.hiddenPassword.substr(
            0,
            this.form.hiddenPassword.length - restPartLength) +
          inserted + 
          this.form.hiddenPassword.substring(this.form.hiddenPassword.length-restPartLength, this.form.hiddenPassword.length);
      }
      this.form.password = this.form.password.replace(/./g,'*');
    }
  }
...

new Vue({ 
el: "#test",
data: {
form: {
        hiddenPassword: '',
        password: ''
      }
},
methods: {
test: function (e) {
let caretPosition = e.target.selectionStart
let restPartLength = this.form.password.length - e.target.selectionStart
if (this.form.hiddenPassword.length > this.form.password.length) {
        this.form.hiddenPassword = this.form.hiddenPassword.substr(0, caretPosition) + 
          this.form.hiddenPassword.substring(this.form.hiddenPassword.length-restPartLength, this.form.hiddenPassword.length);
      } else {
let inserted = this.form.password.replace(/\*/g,'');
        this.form.hiddenPassword =
          this.form.hiddenPassword.substr(0, this.form.hiddenPassword.length - restPartLength) +
          inserted + 
          this.form.hiddenPassword.substring(this.form.hiddenPassword.length-restPartLength, this.form.hiddenPassword.length);
      }
this.form.password = this.form.password.replace(/./g,'*');
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<div id="test">
<input type="text" v-model="form.password" @input="test" />
{{ form.hiddenPassword }}
</div>

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

Tips for updating checkbox values in the database to 1 when selected and 0 when deselected

Managing Database Information <?php if(isset($_POST["insert"])) { $conn = mysqli_connect("localhost", "root", "", "databaseappfeature"); if(isset($_POST["insert"]) == "1"){ $query = "UPDATE appfeature SET feature_switch = ('".$_POST["ins ...

Tabulator automatically inserted 'numrow' after retrieving the data

I have a table of undetermined information (consisting of various columns and rows). I am now at the point where I need to utilize the function table.updateData(), but this function specifically requires the column id to be present in the data structure. S ...

Arranging by upcoming birthday dates

Creating a birthday reminder app has been my latest project, where I store names and birthdays in JSON format. My goal is to display the names sorted based on whose birthday is approaching next. Initially, I considered calculating the time until each pers ...

Experimenting with Nuxtjs application using AVA and TypeScript

I'm in the process of developing a Nuxt application using TypeScript and intend to conduct unit testing with AVA. Nonetheless, upon attempting to run a test, I encounter the following error message: ✖ No test files were found The @nuxt/typescrip ...

Changing innerHTML in CoffeeScript

Are there other options instead of using the 'innerHTML' property in CoffeeScript? In JavaScript, you typically write something like this: document.getElementById('element').innerHTML = "blah_blah" Is there a different approach to ac ...

An unexpected error occurred while attempting to retrieve data from Firebase and display it in another component

An error occurred: Unhandled Runtime Error Error: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components) but got undefined. This could be due to forgetting to export your component from the defi ...

Discover the joy of reading with wrap/unwrap to consume more content in less

I am experimenting with a 'read-more read-less' feature using a wrap method that currently only works for the 'show more' functionality. So, to clarify, if the text exceeds a certain length, I truncate it and insert a read-more-link ( ...

Unable to engage with MUI stepper and modify a value

I am hoping to utilize an MUI stepper in place of a Select component. The current Select component is being utilized to signify the status of the document that the user is currently working on (New, In Progress, Complete, etc.). While I have successfully d ...

Translate the DateTime to the local time zone

As a newcomer to AngularJS, I am working on capturing a DateTime attribute in the UI and passing it to an Odata endpoint. However, the time being sent is not in the current local time. How can I convert this time to local time before sending it to the Odat ...

Troubleshooting "These dependencies were not found:" error message during deployment on Netlify, despite successful execution of yarn run serve on local machine

Currently, as I am creating a website using Vue.js, yarn, and Netlify. The build process works smoothly on my local machine when running yanr run build. However, upon deploying it through Netlify, an issue arises: 5:17:55 PM: failed during stage 'bui ...

Revamping this snippet - JavaScript with NodeJs

Currently working on a basic CRUD application, encountering an issue with obtaining the auto-incrementing value for the latest account in MongoDB. To provide more context, I've included the snippet below to achieve the following: 1) Conduct validati ...

When a specific condition is met, Jquery can automatically execute a function contained

I am trying to slowly reveal the h1 tag using jQuery for demonstration purposes. The scroll function is working when I manually click to initiate it, but I am having trouble triggering it automatically. I feel like I might be missing something simple and ...

The 'style' property is not found within the 'EventTarget' type

Currently, I am utilizing Vue and TypeScript in an attempt to adjust the style of an element. let changeStyle = (event: MouseEvent) => { if (event.target) { event.target.style.opacity = 1; Although the code is functional, TypeScript consist ...

Determine if the user's request to my website is made through a URL visit or a script src/link href request

Presently, I am working on developing a custom tool similar to Rawgit, as a backup in case Rawgit goes down. Below is the PHP code I have created: <?php $urlquery = $_SERVER['QUERY_STRING']; $fullurl = 'http://' . $_SERVER['SE ...

What could this error be in Chrome console: "Uncaught SyntaxError: Unexpected token ':'"

Why am I getting this error in the Chrome console: "Uncaught SyntaxError: Unexpected token ':'"? I have a JSON file located at the root of my application: <script src="levels.json"></script> Here is the content of my JSON file: { ...

Utilizing HTML and jQuery to load a dynamic URL within a div placeholder

I'm experiencing some difficulty with loading a custom URL. Essentially, the user will click on a series of navigation links that will dynamically load the relevant content in a tabbed bootstrap jumbotron. The navigation links vary based on data store ...

Explore the extensive JSON link for redirecting

I have an issue with accessing the HATEOS link example on PayPal. My browser is showing a syntax error when I try to access the link. SyntaxError: missing ) after argument list [Break On This Error] alert(links.1.href); (line 32, col 15) The JSON d ...

Create a scrollable div within a template

After discovering a template that I want to use for my personal project, I noticed a missing element... There's a div where content can be added. That's fine, but what if I add more content than fits in the space provided? The whole website beco ...

"Trying to refresh your chart.js chart with updated data?”

Greetings! I have implemented a chart using chart.js and here is the corresponding code: let myChart = document.getElementById('myChart').getContext('2d'); let newChart = new Chart(myChart, { type: 'line', data: { labels: ...

I am experiencing difficulties with displaying my array of JSX elements in the render function of my ReactJS application. What could be

I am currently working on a trivia application and encountering an issue with inserting an updated array of "Choice" elements for each question. Despite my efforts, whenever I attempt to insert an array of JSX elements, the array appears blank. This is qui ...