Vue automatically clears the INPUT field when disabling it

Have you ever noticed why Vue resets a text input field when it's set to disabled? This behavior is not observed with plain Javascript and also doesn't affect textarea fields.

var app = new Vue({
  el: '.container',
  data: {
  disabled: false,
  fn: "John",
  ln: "Smith",
  com: "My comment here..."
  },
  methods: {
  vue_disable() {
  this.disabled = !this.disabled;
  }
  }
});

function js_disable() {
  document.getElementById("first_name").disabled = !document.getElementById("first_name").disabled;
  document.getElementById("comment").disabled = !document.getElementById("comment").disabled;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
  <h1>Vue disable fields</h1>
  
  <p>22 Aug 2019</p>
  
  <p>Why does an INPUT text field reset when I set the field to disabled with Vue? It doesn't happen with pure Javascript, and doesn't happen with a TEXTAREA.</p>
  
  <p>Type something new into the First Name field then click the first button. The value you entered disappears and the original value is substituted.<p>

<form>
  <div class="form-group">
    <label>First Name</label>
      <input type="text" class="form-control" id="first_name" :disabled="disabled" :value="fn"/>
  </div>
  <div class="form-group">
    <label>Last name</label>
    <input type="text" class="form-control" id="last_name" :value="ln"/>
  </div>
  <div class="form-group">
    <label>Comment</label>
    <textarea rows="4" class="form-control" id="comment" v-html="com" :disabled="disabled">

      </textarea>
  </div>
  <p>
    <button type="button" class="btn btn-default" @click="vue_disable">Disable / Enable 'First Name' and 'Comment' fields with Vue</button>
  </p>
</form>
    <p>
      <button type="button" class="btn btn-default" onclick="js_disable()">Disable / Enable 'First Name' and 'Comment' fields with Javascript</button>
  </p>

</div>

https://codepen.io/MSCAU/pen/jONVRRj

Answer №1

It is recommended to utilize the v-model directive rather than using :value

According to the information provided in the guidelines:

The v-model directive should be employed for establishing two-way data bindings on form inputs, textareas, and select elements.

The value attribute simply sets the initial value for the input field.

In Vue.js, getter/setters are included in all properties within the data object via Object.defineProperty. When a dependency's setter is activated, it alerts the watcher and triggers a re-render of the component (source). As you modified the disabled property, the whole component was re-rendered and the value was set to whatever is present in the data object.

var app = new Vue({
  el: '.container',
  data: {
    disabled: false,
    fn: "John",
    ln: "Smith",
    com: "My comment here..."
  },
  methods: {
    vue_disable() {
      this.disabled = !this.disabled;
    }
  }
});

function js_disable() {
  document.getElementById("first_name").disabled = !document.getElementById("first_name").disabled;
  document.getElementById("comment").disabled = !document.getElementById("comment").disabled;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
    <p>
      <form>
        <div class="form-group">
          <label>First Name</label>
          <input type="text" class="form-control" id="first_name" :disabled="disabled" v-model="fn" />
        </div>
        <div class="form-group">
          <label>Last name</label>
          <input type="text" class="form-control" id="last_name" v-model="ln" />
        </div>
        <div class="form-group">
          <label>Comment</label>
          <textarea rows="4" class="form-control" id="comment" v-html="com" :disabled="disabled">
      </textarea>
        </div>
        <p>
          <button type="button" class="btn btn-default" @click="vue_disable">Disable / Enable 'First Name' and 'Comment' fields with Vue</button>
        </p>
      </form>
      <p>
        <button type="button" class="btn btn-default" onclick="js_disable()">Disable / Enable 'First Name' and 'Comment' fields with Javascript</button>
      </p>

</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

Disabling a specific tab in an array of tabs using Angular and Typescript

Displayed below are 5 tabs that can be clicked by the user. My goal is to disable tabs 2 and 3, meaning that the tab names will still be visible but users will not be able to click on them. I attempted to set the tabs to active: false in the TypeScript fi ...

Encountering a 404 Error while using GetStaticPaths in NextJs

Having issues with Next JS dynamic routes resulting in a 404 Error. Initially attempted debugging by setting it up dynamically, then manually at http://localhost:3001/question/62e7b69ca560b1c81aa1a853 but still encountering the same issue. Tried toggling f ...

Disabling an image is similar to deactivating a button

document.getElementById("buttonName").disabled = true; I have successfully disabled a button using the code above. However, I am now facing a challenge with using pictures as buttons that have an onClick function. Is there a way to disable the onClick fun ...

Having trouble with Javascript not detecting when it's empty?

Recently, I have been attempting to modify the color of a submit button when a form is empty. As a beginner in this area, I am somewhat puzzled as to what mistake I might be making. I will share the current code with you in hopes of receiving some guidance ...

Idea fails to detect imports

I have been attempting to use Angular2 in IntelliJ IDEA IDE. Although my code is valid (I have tried compiling and executing it), the IDE keeps showing me this error: https://i.stack.imgur.com/w6wIj.jpg Is there a way to configure IntelliJ IDEA to hide t ...

Update overall font size to be 62% for a consistent look across the website

Recently, I developed a browser extension that adds an overlay button to the LinkedIn website. Everything was running smoothly until I discovered that LinkedIn uses a global font-size: 62,5% that completely messes up my design.. https://i.stack.imgur.com ...

Uncontrolled discord bot flooding with messages despite being set to send messages only once every 60 seconds

const Discord = require('discord.js'); const { Client, MessageAttachment } = require('discord.js'); const client = new Discord.Client(); client.once('ready', () => { console.log("Ready!") }) client.on(&apos ...

Using the window.prompt function to send information to specific fields in a MySQL database is not functioning correctly. I am looking for assistance with this issue

Currently, I am attempting to send some data to a server that is MySQL-based. After running the code below, it seems like there are no errors showing up in the console. Can you please review this code and let me know if you spot any issues? I would really ...

Issue with Videogular: hh:mm:ss Date filter not functioning properly

I am currently working on integrating Videogular into my audio player application. Below are the settings provided in the example code on this particular page: <vg-time-display>{{ currentTime | date:'mm:ss' }}</vg-time-display> ...

Is there a way to cross-reference a city obtained from geolocation with the cities stored in my database, and if a match is found, send the corresponding ID

Here's the script I'm currently working with: <script type="text/javascript"> search = new Vue({ el: '#offers', data: { data: [], authType: '{{uid}}', key : '1', wi ...

Checking if a function gets invoked upon the mounting of a component

I've been working on testing a method call when a component is mounted, but I keep encountering an issue: The mock function was expected to be called once, but it wasn't called at all. Here's the code snippet for the component: <templ ...

What methods are most effective for evaluating the properties you send to offspring elements?

Currently, I'm in the process of testing a component using Vue test utils and Jest. I'm curious about the most effective method to verify that the correct values are being passed to child components through their props. Specifically, I want to e ...

Looking for Precise Matching within JSON Using JavaScript

I've been experimenting with creating a form that submits data and then checks it against a JSON array to see if there's a matching object already present. Here is a snippet of my JSON data for reference: [ { "ASIN":"B0971Y6PQ3 ...

Remove array element by key (not numerical index but string key)

Here is a JavaScript array that I am working with: [#ad: Array[0]] #ad: Array[0] #image_upload: Array[0] 13b7afb8b11644e17569bd2efb571b10: "This is an error" 69553926a7783c27f7c18eff55cbd429: "Yet another error" ...

What is the most effective approach for preventing the inadvertent override of other bound functions on window.onresize?

As I delve deeper into JavaScript, I constantly find myself pondering various aspects of it. Take for instance the window.onresize event handler. If I were to use the following code: window.onresize = resize; function resize() { console.log("resize eve ...

Enhancing React components with Hooks and markers

I'm facing a syntax uncertainty regarding how to update React state using hooks in two specific scenarios. 1) I have a state named company and a form that populates it. In the contacts section, there are two fields for the company employee (name and ...

The new mui v5 Dialog is having trouble accepting custom styled widths

I am facing an issue with my MUI v5 dialog where I cannot seem to set its width using the style() component. import { Dialog, DialogContent, DialogTitle, Paper, Typography, } from "@mui/material"; import { Close } from "@mui/icons- ...

Uploading multiple files simultaneously in React

I am facing an issue with my React app where I am trying to upload multiple images using the provided code. The problem arises when console.log(e) displays a Progress Event object with all its values, but my state remains at default values of null, 0, and ...

Comparing Angular 5 with --aot and Angular 5 with --aot=false configuration settings

I am having an issue with my Angular application using Angular 5.0.0 and rxjs ^5.5.2. When I run the command ng serve --aot=false, everything works fine. However, when I use ng serve --aot, I encounter the following error: core.js:1350 ERROR Error: Uncaug ...

Experiencing a problem with my JavaScript code in Node.js due to an asynchronous issue arising when using a timeout

My goal with this code is to retrieve JSON questions and present them to the user through the terminal. The user has 5 seconds to respond to each question before the next one appears. However, I encountered an issue where the next question times out automa ...