Adjust input width based on content in VueJS

Is it possible to achieve the following using (Pug & CoffeeScript):

input(placeholder="0", v-model.number="order[index]" v-on:change="adjustInput")
...
adjustInput: ->
    event.target.style.width = event.target.value.length + 'ch'

Even though this code works when manually changing the input in the browser, it doesn't update the width if the change is made through v-model. How can I ensure that the input width adjusts even when the change is due to Vue reactivity?

Answer №1

Take a look at this code snippet, but make sure to double-check the font size for both the input and the fake_div element.

var app = new Vue({
  el: '#app',
  data() {
  return {
    order: 1, // your value
    fakeDivWidth: 10, // initial width set to 10px for input
  };
},
watch: {
  order: {  // listen for changes in input value
    handler(val) {
      this.inputResize();
    },
  },
},
methods: {
  inputResize() {
    setTimeout(() => {
      this.fakeDivWidth = this.$el.querySelector('.fake_div').clientWidth;
    }, 0);
  },
},
})
.fake_div {
  position: absolute;
  left: -100500vw;
  top: -100500vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <input placeholder="0" v-model.number="order" v-bind:style="{width: fakeDivWidth + 'px'}" >
<div class="fake_div">{{ order }}</div> // fake_div is necessary to match input width
// This block serves as a visual aid to ensure the input width matches that of the div
  </div>

Answer №2

Give this a try:

input(placeholder="0", v-model.number="order[index]" v-on:change="adjustInput" :style="{width: reactiveWidth}")

// Your secret Vue code
data() {
   return function() {
       reactiveWidth: 100px; // (some default value)
   }
},
methods: {
  adjustInput() {
     this.reactiveWidth = event.target.value.length + 'ch'
  }
},
computed: {
   reactiveWidth() {
     return this.number + 'ch';
  }
}

The code provided may need some adjustments since I don't have all the details. By simply binding this.number to order[index], the input width is not being affected. The computed property monitors changes in number.

Answer №3

A simple solution for me would be to utilize a contenteditable span instead of the input field to encase the text:

<script setup>
import {reactive} from 'vue'

const state = reactive({
    input: 'The width of this will adjust based on the text entered'
})
</script>

<template>
    <span class="input" @input="e => state.input = e.target.innerText" contenteditable>{{state.input}}</span>
</template>

This mirrors the functionality of v-model=state.input

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

What is the best approach for adding variable rows to a Postgres junction table: should you concatenate a query string, utilize multiple queries, or explore alternative methods

Below is the code snippet for handling a variable-length list of tags and inserting data into the database: // JSON object from req.body { "title": "title", "reference": "1213", "noteType": &q ...

What is the method for configuring my bot to forward all logs to a specific channel?

const logsChannel = message.guild.channels.cache.find(channel => channel.name === 'logs'); I am looking to set up my bot to send log messages for various events, like member join/leave or message deletion, specifically in a channel named &apo ...

Setting the attribute dynamically for a select box with multiple choices

In my form, I have multiple choice select boxes styled using bootstrap select. Since the app is developed in Express, I am having trouble retrieving the selected values due to bootstrap select creating a div and a list for user interaction. To tackle this ...

Using the async.waterfall function in an Express application

Query: I'm encountering an issue with my express.js code where, upon running in Node.js, an empty array (ganttresult) is initially displayed. Only after refreshing the browser do I obtain the desired result. To address this problem, I have attempted ...

update the componentWillMount() function

I am currently exploring the code found at https://github.com/Spyna/react-store/blob/master/src/createStore.js What adjustments do I need to make in order to align with the deprecated componentWillMount lifecycle method? CreateStore const createStore = ...

Having trouble adjusting the color on Material UI select in ReactJS?

Here is the code snippet I am working with: const useStyles = makeStyles({ select: { '&:before': { borderColor: 'white', }, '&:after': { borderColor: 'white&apos ...

Is there a way to determine if a container is overflowing at the top?

Currently, I am using Puppeteer to scrape Slack. My goal is to confirm whether I have scrolled to the very top of the channel feed. The issue arises because the channel feed does not actually scroll, making it impossible for me to utilize the method outli ...

Customizing Webpack 4's Entry Point

Below is the layout of my project: -node_modules -src -client -js -styles -views -index.js -webpack.config.js -server -.babelrc -package -package-lock -README.md -webpack ...

Tips for directing your attention to an input element within a v-for loop in Vue.js

I have implemented a v-for loop to display all my gifs in my Vue.js application. However, I am facing an issue where when I write a comment in one input, it is being replicated in all the inputs of all the gifs. I want the focus to be solely on the input r ...

The default route in Laravel is not functioning properly in conjunction with Vue.js

I am currently working on a single page application with Laravel and Vue, but I'm facing an issue where the index component is not loading upon initial page load. In my web.php file: Route::get('{any}', function () { return view('welco ...

Ways to refresh a canvas element without requiring a full page reload

My goal is to restart a canvas on a website without reloading the page, making the restart dynamic. However, I've noticed that after multiple restarts, the animation slows down and memory usage increases. The situation is complicated by my use of Met ...

Why is the response undefined when I resize an image twice using a JavaScript promise chain?

When I attempt to resize an image using the sharp library twice in my route handler, the result returned is undefined. Despite the resized images being displayed, it seems that calling image.resize and .toBuffer() multiple times is causing corruption in th ...

The dropdown options for the input type file in Vuejs PWA are not appearing

I have created a Vue.js progressive web app that allows users to easily upload images from their mobile phones. While the app typically functions well, there is an issue where upon downloading the app to the homescreen, the image upload feature sometimes b ...

Screen JSON data by applying filters

In my current project, I am working on extracting data from a JSON file and presenting it to the user in a way that allows them to input values that match the expected data. My goal is to show different sections of the screen at different times. The initi ...

The link in Next.js is updating the URL but the page is not refreshing

I am facing a peculiar issue where a dynamic link within a component functions correctly in most areas of the site, but fails to work inside a specific React Component - Algolia InstantSearch (which is very similar in functionality to this example componen ...

Is there a way to delay loading 'div' until a few seconds after the 'body' has been fully loaded?

Is there a way to delay the appearance of the "text-container" div after the image is displayed? I have attempted to achieve this using JavaScript with the following code: <script> window.onload = function(){ var timer = setTimeout("showText()",700 ...

Content OverFlow: DropDown Menu is not overlapping the content, but rather pushing it downwards

In my webpage, I have a drop-down menu that traditionally pushes the content below it down to make space for its items. However, I want the drop-down to overlap the contents below without affecting their position. I've tried various solutions, such a ...

Error: An error occurred because the program attempted to read properties of a null value, specifically the property "defaultPrevented"

There seems to be an issue with a script error involving both the bootstrap alert and my own close alert tag. I have a script set up to automatically close alerts after 2.5 seconds when certain user actions trigger them, such as creating a blog post or del ...

Adding flair to the encompassing container

Below is the HTML code that I am working with: <div class="um-field field-date"> <p class="form-row " id="date_field"> <label class="date"> <input data-label="Date" data-value="" type="date" class="input-date um-frontend-f ...

Conceal the overflow from absolutely positioned elements

I've gone through all the similar examples but still struggling to find the correct solution. My issue involves a basic Side Menu that toggles upon button click. Within the menu, there is a list of checkboxes positioned absolutely with the parent con ...