Apply a border to the input field when the user enters or leaves the field, only if the value is

I am managing a few input fields and storing their information in an object. My goal is to click on an input field to focus on it, and if the field is empty or has a length greater than or equal to 0, I want it to display a red border. If I type something in the field, the red border should be removed. Also, even if the value of the input is zero and I exit the field, the red border should disappear. I have a function that accomplishes this, but when I apply it to multiple inputs, clicking on one input affects the others. How can I ensure each input behaves independently?

inputs

        <div class="superficie info" :class="{'input-error' : validInput}">
             <label>area</label>
             <input type="number" v-model="objInfo.area" @focus="inputFocus" @blur="inputBlur" @input="validatingInput">
        </div>
    
        <div class="address info" :class="{'input-error' : validInput}">
            <label>address</label>
            <input type="text" :value="objInfo.address" @focus="inputFocus" @blur="inputBlur" @input="validatingInput">
        </div>

functions

const validInput= ref(false)
const inputFocus = (e) => {
    if(objInfo.value.area === ''){
        validInput.value = true
    }  
}

const inputBlur = (e) => {
    validInput.value = false
}

const validatingInput = () => {
    if(objInfo.value.area === ''){
        validInput.value = true
        return
    }
    validInput.value = false
}

Answer №1

Is there a way to independently mark each input field when clicked, instead of them both being marked at the same time?

It may appear that one input is being marked over the other, but in reality, they are both receiving the input-error class simultaneously due to using a single variable validInput to track validation across all fields. This could be misleading as the focus border of the active input might disguise the error style applied.

In my attempt to replicate the issue, I suggest creating separate variables to monitor the validation status of each input individually. For instance:

const inputValidity = ref({
  areaInput: false,
  addressInput: false,
})

You can then target and update these properties like this:

<template>
  <input @input="validateAreaInput" />
</template>

<script>
...

const validateAreaInput = (input) => {
  if (input) {
    inputValidity.value.areaInput = true;
  }
  inputValidity.value.areaInput = false;
}
</script>

To enhance this concept further, consider defining validator functions for specific cases and associating them with data properties. Alternatively, you can utilize existing libraries such as:

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

"Enjoying the convenience of a stationary header while browsing on your smartphone

Hey there! I'm currently facing an issue with my website's fixed horizontal nav bar when zooming in on a mobile device. After doing some research, it seems the only solution is to implement some javascript. I came across a jquery fix (see below) ...

Display various React components for widgets

I am looking to display multiple instances of a widget in html. I have 3 divs with the same id, each with different attributes, and I want to render my react component three times on the page. Currently, I am only able to display the first component. Here ...

Effortless navigation with smooth scrolling on anchor links in react/next.js

Can smooth scrolling be achieved using only CSS when clicking on an anchor link within a react component? ... render( <a href="#smooth-link">Link To There</a> .... <div id="smooth-link"> .... ...

The CSS ::after selector is experiencing a decrease in animation speed

There is a dropdown menu set to fade in once a link is clicked. Everything works well, the menu fades in properly. However, when clicking off and triggering a function that fades out the dropdown, the triangle on top of the box fades out slightly slower th ...

An error occurred: gyp ERR! stack - The command `python -c import sys; print "%s.%s.%s" % sys.version_info[:3]` has failed

While attempting to npm install in a Vue project, I encountered an error even after running vue create (name): npm ERR! gyp verb check python checking for Python executable "c:\Python310\python.exe" in the PATH npm ERR! gyp verb `which` ...

What is the best method to reset values in ngx-bootstrap date picker?

At the moment, it is only accepting the most recently selected values. To see a live demo, click here. ...

What is causing the beforeUpdate hook in Sequelize to fail?

I have a user model with 2 hooks that I am working on. User.beforeCreate(setSaltAndPass) User.beforeUpdate(setSaltAndPass) The first hook works perfectly fine, but the beforeUpdate hook is not triggering as expected. As per the documentation, there should ...

Generating observables from form submission event

Note: I am completely new to Angular and RXJS. Currently, I am working on a simple form where I want to create an observable. The goal is to listen for submit events and update a value within the component. However, I keep encountering an error message sa ...

Map Row is unreturned

I am having trouble when attempting to map a JSON response from a MySQL query as I am receiving no response: data: NULL This is the code in question: const audience = rows.map((row) => { db.query(CountAudiences, [row.campaign], function(err, count ...

Error: Undefined Function [Thinkster.io's Angular Tutorial Chapter 4]

Currently working on the Angular Tutorial provided by Thinkster.io and enjoying every bit of it. However, I've hit a roadblock in Chapter 4 that seems impossible to overcome. Whenever I attempt to execute a Post or Delete action, I encounter the follo ...

Iterate through the object received from the node promise and pass it to the subsequent .then method

After grappling with this issue for what feels like an eternity, I find myself immersed in learning about Node.js and trying to grasp the concept of promises. My current challenge involves retrieving data from the Spotify API, starting with fetching my ow ...

Issues arise when attempting to utilize jQuery to print a string once a button is pressed

I am trying to display a string on the webpage when the user clicks a button. Below is the HTML code: <p> <h1 class="text-center" id="notif"> </h1> </p> Here is the relevant part of the script: $("#btn_My").click(functio ...

Filtering data in VueJs using Vuetify's v-tabs feature

I am currently utilizing NuxtJs, a lightweight version of the VueJS framework. My goal is to implement a data filtering functionality based on tab clicks. The objective is to display the data in alphabetical order and filter them accordingly when tabs are ...

Tips on handling multiple text field validation in material-ui for react?

Currently, I am working on developing a form using Material-UI and React.js where I need to validate two TextField components. My goal is to apply the same error and textHelper props to both TextFields. Below is a snippet of my code for reference. Any sugg ...

Differences between Jquery's Find Method and ID Attribute

In my search for efficiency, I am currently exploring ways to quickly access an element. Which method is faster: $('body').find('#elemID'); vs. var id = $('#elemID'); ...

Creating a table in VueJs and populating it with values retrieved from an MSSQL database in a .NET Core web application

I am developing a table within a .NET Core Web Application that includes multiple rows and columns filled with data retrieved from a MSSQL server through a WEB API Given the need for numerous rows and columns, I am considering using a for loop inside my & ...

How can I add a string before a hashtag(#) in AngularJS URLs?

Can we add a prefix to the # symbol in angular.js URLs? For instance: let's say we have a site: http://example.com/ then when I click on the CSharp page, it redirects to http://example.com/#/csharp when I click on the AngularJS page, it redi ...

Ways to transfer a variable from a component's function in Vue?

Can anyone help me figure out how to pass a variable from a function within a Vue component? Here's the code I've been working with: export default { name: 'app', data: function () { return{ city1: '&a ...

Dragging the world map in D3 causes it to appear jumpy and erratic

I'm currently working on a Vue project to create an interactive world map that allows users to drag and zoom. I've attempted to integrate D3 for this purpose, but encountered an issue where the map jumps to the bottom right of the page whenever I ...

Exploring the Impact of Escaped Characters in VueJS

I seem to have encountered an issue while working with VueJS. It appears to be a bug, though I cannot confirm it completely. Even when I use escaped double curly braces in HTML, they still get evaluated by the engine. https://jsfiddle.net/judda/ge042znc/1 ...