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

Problem with ngStyle: Error indicating that the expected '}' is missing

I encountered an error in the Chrome console when trying to interpret the code below: <div [ngStyle]="{'width': '100%'; 'height': '100%'; 'background-size': 'cover'; 'background-repeat&ap ...

Display popup depending on the post's identification number

Currently, I'm in the process of integrating Sanity into my blog. Using the json object returned from a query with useState, I managed to display my posts successfully. However, I am now faced with the challenge of populating a React-Modal with the ap ...

Trouble encountered while attempting to choose a single checkbox from within a v-for loop in Vue.js?

<div id="example-1"> <ul> <input type="text" v-model="searchString" placeholder="Filter" /> <p>sortKey = {{sortKey}}</p> <li v-for="item in sortedItems"> <input class="checkbox-align" type="checkbo ...

Issue: Cannot assign type 'Promise<PostInfo>[]' to type 'PostInfo[]' while updating state

At the moment, I am facing an issue with my function that fetches an API and updates state. Specifically, I encounter an error when attempting to assign a Promise to the state. type DataState = { postList: Array<PostInfo>: }; const [state, setSt ...

I currently have an array of strings and wish to print only the lines that include a specific substring

Here i want to showcase lines that contain the following strings: Object.< anonymous > These are multiple lines: Discover those lines that have the substring Object . < anonymous > Error: ER_ACCESS_DENIED_ERROR: Access denied for user ' ...

Ways to integrate PHP MySQL with NodeJS and SocketIO

Currently, I am working on developing a chat application. I have successfully implemented features like creating accounts, logging in, selecting, viewing, and more using PHP MySQL. Now, I am venturing into the Instant Messaging aspect by utilizing NodeJS a ...

Error encountered while making a REST API call in Ajax: Unforeseen SyntaxError: Colon unexpected

I am currently troubleshooting my code to interact with a REST API. My platform of choice is "EspoCRM" and I aim to utilize its API functionalities. The official documentation recommends using Basic Authentication in this format: "Authorization: Basic " ...

Dealing with errors such as "Failed to load chunk" can be resolved by implementing lazy-loading and code-splitting techniques

Our team is currently working on a Vue.js application using Vue CLI 3, Vue Router, and Webpack. The routes are lazy-loaded and the chunk file names include a hash for cache busting purposes. So far, everything has been running smoothly. However, we encoun ...

The width of the plotbands on the yAxis of a stacked bar graph is adjusting as the series are dynamically toggled,

https://ibb.co/h7tmwtr https://ibb.co/syRTyPG For the first time, I have included 5 plot bands which looked great. However, when I added a series and toggled it on a stacked bar graph, the plot bands' width started increasing. I want to maintain the ...

What are the steps to achieve consistent response behavior in POSTMAN that matches that of a web browser?

Below is an example of my code: const express = require('express'); const app = express(); app.get('/', function (req, res) { res.setHeader('Content-Type', 'text/html'); res.write("First \n"); set ...

Can you explain the distinction between locating an element by its class name versus locating it by its CSS selector?

Class name: var x = document.getElementsByClassName("intro"); CSS selector: var x = document.querySelectorAll("p.intro"); I'm a bit puzzled, are there any distinctions between the two methods or are they essentially the same? ...

Is it possible for the like button to display specific information when clicked?

When working with a looping structure in Ionic and Angular, which includes post content such as text, photos, and videos, I am encountering an issue with selecting specific data when clicking on the like button. How can I ensure that only the data associat ...

Utilizing Vuex in Vue with vue-enterprise-boilerplate: A Step-by-Step Guide

I am attempting to incorporate Vuex into my project using the chrisvfritz/vue-enterprise-boilerplate template. However, I am facing uncertainty regarding how to proceed. Within the <script> section of the "courses.vue" view component, the code appea ...

Obtain data attributes using JQuery's click event handler

I'm facing an issue with a div structure setup as follows: <div class='bar'> <div class='contents'> <div class='element' data-big='join'>JOIN ME</div> <div class=& ...

Why is JavaScript unable to fetch JSON data from C when the uint32 value is a multiple of 256 plus 10?

After receiving some helpful feedback, I decided to make some changes to this question that I posted yesterday. The title and content have been edited for clarity based on the new information I've learned. Recently, I've been utilizing C code to ...

What is the process for taking a website project running on localhost and converting it into an Android web application using HTML, CSS, and JavaScript

Looking for recommendations on how to create an Android web application using HTML, CSS, and JavaScript. Any suggestions? ...

Clicking a button in JavaScript can pass an ID by triggering an onClick

Here is the function that triggers when the button is clicked <button type="button" class="btn btn-info " onClick= "show('<?php echo $data ?>')" name="show" >Show</button> This is the show function defined in the .js file f ...

Instead of automatically playing, Youtube videos either remain idle or display suggested videos

I am trying to play a specific moment of an embedded Youtube video using some javascript code. At the specified time, I execute the following code: document.getElementById("video").src= "https://www.youtube.com/embed/...?autoplay=1&start=212"; where ...

The functionality of findDOMNode is no longer supported

My website, built using React, features a calendar that allows users to select a date and time range with the help of the react-advanced-datetimerange-picker library. However, I encounter some warnings in my index.js file due to the use of <React.Stric ...

Properly aligning text with checkboxes using HTML/CSS and tags like <span> or <div>

My goal is to have the text displayed as a block in alignment with the checkbox, adjusting based on the sidebar's width. For reference: Current Layout Preferred Layout I have shared the code on CodePen (taking into account screen resolution and wi ...