Creating a text box that displays an inverted input

Hello, I'm looking to create a text box where if I input 1 then 2, it will display 21. Then if I enter 3, it should show 321. I am currently using Vue.js on my front end.

Here is what I have attempted so far:

I experimented with methods such as watching for changes and updating the value, but ran into an issue with infinite loops.

I also tried utilizing key-down, keypress, and keyup, but encountered difficulties with registering the first input.

Another attempt involved using keyup, however, the problem arose where it would initially display the user input before reversing it.

Answer №1

HTML Example:

<input v-model="textInput" @input="reverseText"/>
{{ reversedText }}

Javascript Code:

data() {
 return {
  textInput: '',
  reversedText: ''
 }
}

methods: {
 reverseText() {
  this.reversedText = this.textInput.split("").reverse().join("")
 }
}

Answer №2

It seems like you're looking to dynamically invert user input in real time using @keyup, while still displaying the original sentence in the input field. After some research, I discovered a workaround as v-model doesn't allow for changing input while typing. The solution involves using absolute positioning and two input fields – one hidden on top for input and one visible at the bottom for output.

To see the live preview, check out: Sandbox preview

<template>
  <div class="hello">
    
    <div class="invert">
      <input type="text" v-text="input" class="input"   @keyup="handle" >
      <input type="text" v-model="output" class="output"  >
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      input : '',
    }
  },
  computed : {
    output (){
        return this.input.split("").reverse().join("");
    }
  },
  methods : {
    handle(event) {
         this.input = event.target.value;
    }
  }
}
</script>
<style scoped>
  .invert {
    position : relative ;
    width: 200px;
    height: 20px;
    margin: 0 auto;
  }
  .output , .input{
    position: absolute;
    width: 100%;
    right: 0;
  }
  .input {
    z-index: 5;
    opacity : 0 ;
  }
    .output {
    z-index: 0;
    opacity : 1 ;
  }
</style>

Best Solution

One Input!

If you notice any flickering when the input initially appears non-inverted, it may be due to v-model binding occurring before the handle function. Check out the updated version here:

Sandbox preview

<template>
  <div class="hello">
    <div class="invert">
      <input type="text" v-model="input" class="input" @input="handle" />
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      input: "",
    };
  },

  methods: {
    handle(event) {
      if (this.input.length > 1) {
        this.input =
          this.input[this.input.length - 1] +
          this.input.substring(0, this.input.length - 1);
      }
    },
  },
};
</script>

Second Option Two Inputs

If you encounter the non-inverted input issue, you can go back to using two inputs due to the limitation of v-model binding speed. However, this time, utilize transparency instead of opacity for selection ability. Update the style with:

sandbox preview


.input {
  z-index: 5;
  background: transparent;
}


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

Retrieve identical values from an array and display them using Vue.js

I am working with a product array that includes id, name, and category data for 5 products. For example, let's say there are 3 products assigned to the mobile category and 2 products assigned to the computer category. What is the best approach to rend ...

The function inputLocalFont.addEventListener does not exist and cannot be executed

Help needed! I created a code to add images using PHP and JS, but I'm encountering an error in my JS that says: inputLocalFont.addEventListener is not a function Here's the code snippet: <div> <img src="<?php echo $img_path.& ...

Tips for inserting HTML-tagged data into a database using AJAX and PHP

var id=$("#id").val(); var status=$("#status").val(); var jtitle=$("#jtitle").val(); function submitData(){ var id=$("#id").val(); var status=$("#status").val(); var jtitle=$("#jtitle").val(); var jdesc=tinyMCE.acti ...

Utilizing D3 for translation by incorporating data from an array within d3.js

I need assistance with drawing rectangles in an SVG where the translation data is stored in an array. Below is the code: var vis=d3.select("#usvg"); var rectData=[10,21,32,43,54,65,76,87,98,109]; vis.selectAll("rect").data(rectData).enter().append("rect ...

Node.js Express refuses to serve .js files with absolute URLs

I have encountered a perplexing issue with two files located in /public/widget, namely help.html and help.js http://localhost:8084/widget/help.html When entered into the address bar, it functions normally However, when attempting to access http://local ...

Tips on extracting information from a selected row in a Vuetify Datatable

My Vuetify Datatable displays information about members. <v-data-table :headers="headers" :items="members" item-key="id" v-model="selected" :search="search" ...

Styler column - Bootstrap-vue - VueJS

The goal is to format the 'from' and 'to' columns in a way that displays their description rather than their code in the table. <b-table id="my-table" hover striped small outlined :items="items" :fields="fields" class="mt-0 mb-0"> ...

When using Lockdown.js with NPM, I encounter a blank file being returned

When using Lockdown.js for NPM, I encountered an issue where the command to generate the lockdown file resulted in an empty file. Here are the links for the dependencies: NPM lockdown git Here is a snippet from my package.json: { "name": "nw", "pri ...

Is it impossible to modify an enumerable attribute within a JSON.stringify replacer function?

I'm having some trouble trying to serialize non-enumerable properties within the replacer function. Can someone point out what might be going wrong in this code snippet? Any help would be greatly appreciated. var obj = {x:1,y:2}; Object.definePrope ...

Is there a way to fix this issue: when updating a child component in Vue.js, it automatically updates all the other children as well?

How can I efficiently update the likes for a specific comment within the parent component Commnet.vue? <template> <v-list class="list" color="white" three-line> <template v-for="cmnt in comments" class ...

The popularity of AJAX in JavaScript is continuing to rise

I am facing an issue with my website that features a configurable 3D object with various properties. Whenever I reload the div containing the 3D object to reflect new properties, the script data keeps adding on. This not only slows down the functionality a ...

When trying to find a substring within a string in JavaScript, the "else if" statement may not be triggered

I'm currently working on creating a Hangman game using HTML and JS. Most of the code is functioning properly, but I've hit a roadblock. For some reason, one part of my if else statement isn't working correctly. Here's the line of code: ...

The timing is off in the Vue Animation Script

I am working on a web api project and I have a specific requirement. I want to play an animation on one of my HTML spans. The Vue returns a number, and I need that number to animate increasing from 00.00% up to its actual value. I found a JavaScript scri ...

Unable to modify headers after they have already been sent to the client - an error has occurred

I am encountering an issue when trying to redirect the page to another page. Everything works fine with the first post request, but starting from the second one, I keep getting this error message: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after t ...

Unable to preventDefault() function from working within .then method

Snippet: angular .module('mean-starter') .run(run) ; function run($rootScope, Auth, $state) { function stopStateChange (message, event, redirect) { console.log(event); event.preventDefault(); alert(message); if (redirect) ...

Presentation Slider (HTML, CSS, JavaScript)

Embarking on my journey of creating webpages, I am eager to replicate the Windows 10 start UI and its browser animations. However, my lack of JavaScript knowledge presents a challenge. Any help in reviewing my code for potential issues would be greatly app ...

What could be causing the issue with this jQuery selector for the parent form element?

I created a form that connects a button with an attribute, but it's not hiding the parent("form"). However, when I try this, it works. $($("[editFormContent]").attr("editFormContent")).click(function(e) { e.preventDe ...

Is it possible to run my JavaScript script immediately following the execution of npm run build?

Hey everyone! I am trying to run my JavaScript file right after receiving the successful message from npm run build. Currently, I am working on a Vue.js codebase. Is there a way for me to log and create a file in my code repository containing the 'run ...

What is the best way to incorporate tooltips in SVG?

My teacher wants me to display a tooltip on an SVG circle with links and information when we hover over it. They suggested using jQuery UI, but I've done extensive research and nothing has been able to assist me so far. ...

Keep the final item in an array that shares the same attribute

I am working with an array const obj=[{fullCart: 5, halfCart: 4, smu: 3, stowage: 5, index: "FC-093"}, {fullCart: 5, halfCart: 4, smu: 8, stowage: 5, index: "FC-093"}, {fullCart: 5, halfCart: 4, smu: 0, stowage: 5, index: "FC-093 ...