Troubleshooting: Issues with VueJS Class Binding Functionality

In my form, I have an input field that is validated to check if it is empty or not. If the input field is empty, a red border is applied using class binding.

However, when the user focuses on the input field after receiving the error, the error message should disappear. Unfortunately, this functionality is not working as expected. The error message does not go away upon focus.


            new Vue ({
                el: '#app',
                data: {
                    register: {
                        firstName: '',
                    },
                    errors: {
                        firstName: '',
                    },
                },
                methods: {
                    validateLoginForm() {
                        const regsrt = this.register;
                        this.errors = {};

                        if(!regsrt.firstName) {
                            this.errors.firstName = 'First Name is required';
                        } else {
                            this.errors.firstName = '';
                        }
                },

                deleteErrors(errorName) {
                    this.errors[errorName] = '';
                }
            }
          });
    
<div id="app">
  <form action="" method="POST" accept-charset="UTF-8" @submit.prevent="validateLoginForm()">
      <label for="firstName">First Name</label>
        <input 
            :class="{'red-border': errors.firstName}" 
            type="text" 
            @focus="deleteErrors('firstName')"
            v-model="register.firstName">
        <input type="submit" value="Register">
  </form>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.min.js"></script>

JSFiddle: http://jsfiddle.net/6L3shqdk/14/

The desired behavior is that upon focusing on the input field, the error message for the first name should be removed and the red border should disappear due to class binding being set to false. However, this is currently not functioning as intended. Assistance would be appreciated!

Answer №1

Get rid of this paragraph

this.errors = {};

This action completely hinders the ability to react. It essentially replaces an object that has necessary setters (for the firstName property) with a new empty object, which can no longer monitor changes in firstName.

The correct approach is as follows:

validateLoginForm() {
  const regsrt = this.register;

  if (!regsrt.firstName) {
    this.errors.firstName = 'First Name is required';
  } else {
    this.errors.firstName = '';
  }
},

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

The function jQuery[number] did not get executed

Hello, I have been researching this issue and have come across multiple solutions, but unfortunately none of them seem to work for me. I keep encountering the error message "jQuery21006460414978209883_1395689439888 was not called" when making an AJAX call ...

Utilizing AngularJS with Restheart API to streamline MongoDB integration and efficiently parse JSON data outputs

Utilizing RestHeart to expose CRUD functionality from MongoBD. Attempting to call the Rest API from AngularJS and retrieve the JSON output like the one displayed below. My focus is specifically on extracting the name, age, & city fields that are stored in ...

Arrangement featuring two distinct types of tiles

Looking for a way to achieve this layout using just CSS or a combination of CSS and a little JS. Click on my avatar to see the reference image enlarged =) I've tried using floats and display options but haven't been successful. Take a look at htt ...

What is the process for setting up Vue.js and using it in conjunction with Sails JS?

After successfully setting up the backend of my website using Sails JS, I decided to integrate Vue.js into my project. Following the installation of Vue and VueResource through npm install --save, I created an app.js file in my assets/js folder. However, ...

Getting the chosen value from a dropdown menu on form submission using PHP

How to Populate a Combo Box from a Database in PHP? <td>Item Name:</td> <td><select name="items"> <option value="0" selected="selected"> Choose</option> <?php while($row = mysql_fetch_ass ...

Issues with Vue v-for when using variable ranges

totalLoops = 3; Desired output: 1 2 3 Method: <div v-for="i in 3">{{ i }}</div> Issue Encountered: <div v-for="i in totalLoops">{{ i }}</div> I have exhaustively researched and experimented with various sol ...

Press the submit button after receiving the ajax response

Is there a way to manually or programmatically submit a specific page? The catch is that before the submission can happen, a function called create_impi_num(x) needs to be triggered in order to store data using $.post(). The issue at hand: If I set the s ...

I am looking to showcase the information from two separate collections

I am looking to display data from two separate mongoose collections. I have a Member collection and a Property collection. Below is my code for fetching the data: const Property = require('../models/propsSchema') const Members = require(&apo ...

Mobile devices are unable to properly implement the Jquery show/hide feature

Currently, I am working on a small Russian project and facing some challenges with the mobile version of my website: php8098.github.io/breakfast. The issue lies within the first slider where the play button should trigger a modal window to open. I urgentl ...

Utilizing jQuery to attach events to dynamically generated elements

I have a scenario where I am uploading multiple images and inserting them into specific div elements. These divs should toggle a class when clicked. Should I include the part of code that adds the onclick event inside the ajax success function? Your help i ...

Vuejs error: Attempting to access properties of undefined

In my Vue table, I have select options. However, an error occurs when a group is not associated with a machine, which should not happen. The goal is for only "-" to appear in this case. This error is logged in the console and causes the DataTable not to di ...

Error: No package.json file found after publishing npm package with ENOLOCAL

Ecosystem using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="335d435e73051d021d03">[email protected]</a> using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6a8a9a2a386b0fee8f7f7e ...

Leverage selenium to enter data for numerous elements by utilizing xpath

I am new to using Selenium and I am exploring ways to locate a series of input elements using xpath or css. My goal is to iterate over each element and input text into them. For example: <form> value1 <input type="text" placeholder="value1"> ...

Having difficulty installing npm due to version issues while working with Vue

What steps should I take to troubleshoot this issue? PS C:\xampp\htdocs\MOA\agri-app> npm install npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/em ...

reasons why the keypress event may not be triggered

Hello there, I am trying to create a function that simulates pressing the 'tab' key. The function is supposed to restrict input within specific ranges and return the cursor to another range once the limit is reached. Additionally, if a user input ...

Having trouble with the dropdown menu in Bootstrap?

I'm having trouble creating a responsive dropdown menu. When I click on the dropdown items, nothing happens. Here's the code: <div class="navbar-header"> <button type="button" class="navbar-toggel" data-toggel="collapse" data-target="#m ...

Arrange, Explore (Refine), Segment HTML Chart

Is there a way to efficiently sort, paginate, and search (based on a specific column) data in an HTML table? I've explored several JQuery plugins such as DataTable, TableSorter, Picnet Table Filter, but none seem to offer all three functionalities (se ...

What could be causing the 403 Error when using Blogger API with AngularJS?

I'm relatively new to working with 3rd Party APIs and I'm currently exploring how to integrate Blogger's API into my AngularJS website to create a blog feed feature. After setting everything up, I've made a request and received a 200 s ...

Extract information from a lengthy text (vcard)

While scanning data from a vcard QR-code, the string I receive always follows this format: BEGIN:VCARD VERSION:2.1 N:Lastname;Firstname FN:Firstname Lastname ORG:Lol Group TITLE:Project Engineer TEL;WORK:+32 (0)11 12 13 14 ADR;WORK:Industrielaan 1;2250 Ol ...

Establishing updated file path for resources in JavaScript based on environment

I'm currently facing an issue with my external Javascript file that uses the getScript() function to execute another JS file. Both files are located on static.mydomain.com, as I am trying to set up a Content Delivery Network (CDN) for the first time. ...