Difficulty encountered in altering button color when the password and confirm password fields are the same in a Vue.js project?

password: '',
confirmPassword: '',

computed: {
    empty() {
      return this.user.password === '' || this.user.confirmPassword === '';
    },
    equal() {
      return this.user.password === this.user.confirmPassword;
    }
  }
  
 .empty {
          width: 160px;
          height: 50px;
          line-height: 50px;
          text-align: center;
          font-size: 16px;
          font-weight: 600;
          color: #fff;
          background-color: #f68e91;
          border-radius: 10px;
          margin-top: 15px;
          padding: 0 20px;
          cursor: pointer;
          opacity: 0.5; 
          display: flex;
          justify-content: center;
          align-items: center;
          outline: none;
          border: none;
        }
        
        .no-empty {
          opacity: 1.5;
          background-color: #ee1d24;
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input v-model="user.password" type="text">
  
  <input v-model="user.confirmPassword" type="text>
  <button :class="[equal && !empty ? 'empty' : 'no-empty']" :disabled="!equal || empty">Send</button>
                      < /div>

For the above code, I am able to change the color of the button if the fields are empty, and if filled they are not empty, changing the color.

The issue is in the confirmPassword field - if I enter a single character only, it is changing the color of the button. I need it to only change the button color if the password and confirm password match, otherwise show a different color.

Answer №1

Method 1 - Template Styling Without Functions

Step 1: The HTML template will include:

<div id="app">
<input v-model="user.password" type="text" />
<input v-model="user.confirmPassword" type="text" />
<button :class="user.password && user.confirmPassword && user.password === user.confirmPassword  ? 'match' : 'nomatch'" :disabled="empty">
  Send
</button>

Step 2: Include the following scripts:

<script>
export default {
  name: "App",
  data() {
    return {
      user: {
        password: "",
        confirmPassword: "",
      },
    };
  },
  computed: {
    empty() {
      return this.user.password === "" && this.user.confirmPassword === "";
    },
  },
};

Step 3: Apply styles as shown below

<style>
.nomatch {
  width: 160px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
  color: #fff;
  background-color: #f68e91;
  border-radius: 10px;
  margin-top: 15px;
  padding: 0 20px;
  cursor: pointer;
  opacity: 0.5;
  display: flex;
  justify-content: center;
  align-items: center;
  outline: none;
  border: none;
}

.match {
  opacity: 1.5;
  background-color: #ee1d24;
}
</style>

Method 2 - Using Function Handler in HTML template

Step 1: Update the HTML template as follows

<div id="app">
<input v-model="user.password" type="text" />
<input v-model="user.confirmPassword" type="text" />
<button :class="this.matchPassword() ? 'match' : 'nomatch'" :disabled="empty">
  Send
</button>

Step 2: Adjust the script section with the function handler

<script>
export default {
  name: "App",
  data() {
    return {
      user: {
        password: "",
        confirmPassword: "",
      },
    };
  },
  computed: {
    empty() {
      return this.user.password === "" && this.user.confirmPassword === "";
    },
  },
  methods: {
    matchPassword() {
      if (
        this.user.password &&
        this.user.confirmPassword &&
        this.user.password === this.user.confirmPassword
      ) {
        return true;
      } else {
        return false;
      }
    },
  },
};
</script>

Step 3: Remember to update the styles accordingly

<style>
.nomatch {
  width: 160px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
  color: #fff;
  background-color: #f68e91;
  border-radius: 10px;
  margin-top: 15px;
  padding: 0 20px;
  cursor: pointer;
  opacity: 0.5;
  display: flex;
  justify-content: center;
  align-items: center;
  outline: none;
  border:
  
  display: none!;
}

.match {
  opacity: 1.5;
  background-color: #ee1d24;
}
</style>

Both these methods are effective, and you can view a demo here

Answer №2

It seems like you are looking to change the color only when both password values are not empty and are equal, is that right?

If that's the case, your ternary condition is currently only checking for empty, not equal. You can simply adjust the condition in your template like this:

<button :class="[empty || !equal ? 'empty' : 'no-empty']" :disabled="empty">Send</button>

You can apply the same update to the :disabled attribute condition if needed.

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

Exploring Next.js with getServerSideProps

My code has a warning from the console attached. I would appreciate it if someone could help me identify the problem... When I use the "data" hardcoded as props, I can display them in the components, but when I try to fetch from an API, I can retrieve the ...

Vue Js error message: The following dependency could not be found: * core-js/fn/promise

While working on my Vuejs App, I encountered an error related to promises: I received the following error message: "This dependency was not found: core-js/fn/promise in ./src/store/index.js. To resolve this, you can run: npm install --save core-js/fn/promi ...

Reasons why the Express Route fails to store cache while executed in a separate file

My code works fine when it's all in one file, but the caching stops working when I move it to a separate middleware file. Can someone help me understand why the caching isn't functioning properly in my middleware? Here is the working code: var e ...

Alert displayed on console during transition from MaterialUI lab

Whenever I try to run my MUI application, an error pops up in the console It seems you may have forgotten to include the ref parameter in your forwardRef render function. import { LoadingButton } from "@mui/lab"; const LoadData = ({loading,sig ...

Convert XML data into a structured table format

We have an XML file named "servers.xml" that needs to be parsed. This file is located on the same server where we want it to be parsed, in the same folder. <root> <list> <server> <server name="28 Disconnects La ...

Facing an obstacle in Angular as I am unable to view my data

How can I bind the model of my controller in the init function and see the data when the init is called? Index.html <!DOCTYPE html> <html ng-app="I-Sign"> <head> <meta http-equiv='X-UA-Compatible' content='IE=edge&apo ...

Experiencing Excessive Recursion While Dynamically Attaching Click Event Listener With Post Method to a Div Element

I'm encountering 'too much recursion' errors when trying to dynamically add a click handler to specific div tags with the class name 'reportLink'. Despite successfully logging the innerText of the divs, the code fails when attempti ...

Establish a global variable within the utils.js module in a Node.js environment

Hey there, I'm currently in the process of trying to figure out how to properly define a global variable in node.js. I am aware that it's not considered best practice, but in this specific scenario, it seems like the only way to go without involv ...

Steps to releasing JavaScript and asset files on npm

I have created a custom UI component for internal company use and released it on npm. However, after installing the package, I noticed that only the index.js file is showing up in the node_modules directory. I am not utilizing any package builders or ES m ...

Utilizing Axios GET Method with Authorization Header in a Vue Application

Currently, I am attempting to make a GET request using axios to an API that requires an Authorization header. Below is the code I am currently working with: My Code: data () { return { listings: [], AuthStr : 'Bearer ' + JSON.pa ...

What is the process for "dereferencing" an object?

How can you access the properties of an object returned by a function in JavaScript? For instance: var tmp = getTextProperties(); font = tmp.font; size = tmp.size; color = tmp.color; bold = tmp.bold; italic = tmp.italic; While PHP offers the list ...

There was an error during product validation that occurred in the userId field. In the Node.js application, it is required to

I am in the process of developing a small shop application using node.js, express, and mongoose. However, I have encountered an issue when attempting to send data to the MongoDB database via mongoose. Here is the product class I have created: const mongoo ...

Attempting to bind an input parameter using NgStyle in Angular version 2 and above

Issue: I am in need of a single component (spacer) with a width of 100% and a customizable height that can be specified wherever it is used in the HTML (specifically in home.html for testing): number 1 <spacer height="'200px'"></spa ...

There seems to be an issue with AJAX file uploading functionality in Django

I'm facing an issue with uploading files using the onchange event and AJAX. I am only able to get the file path on the backend, not the actual file itself. My goal is to modify the code so that when a PDF file is selected, it automatically gets upload ...

Vue form mysteriously invisible

After attempting to create a Products form using VueJS, I encountered an issue where my localhost simply displayed a blank page upon refreshing. Here is the screenshot of the page Despite restarting XAMPP, the problem persisted with only a blank page bein ...

The overlay feature in Vuetify 3 seems to be malfunctioning following the migration from Vue 2

I have recently migrated a Vue2 project to Vue3 and set up a Vite project. Even though the code from the old Vue2 project works fine, I am facing issues with an overlay functionality in one of my components. Despite setting the overlay to true in data and ...

How to handle and display validation errors in an AJAX post request using express-validator in Node.js/Express

I am in the learning phase with Node and attempting to display validation errors (using express-validator and express 4) when a user submits a form. The validator appears to be functioning properly because when I log the data to the console, everything lo ...

Tips for assigning a JSON object as the resolve value and enabling autosuggestion when utilizing the promise function

Is there a way to make my promise function auto-suggest the resolved value if it's a JSON object, similar to how the axios NPM module does? Here is an example of how axios accomplishes this: axios.get("url.com") .then((res) => { Here, axios will ...

Unable to set options, such as the footer template, in Angular UI Typeahead

I am looking for a way to enhance the results page with a custom footer that includes pagination. I have noticed that there is an option to specify a footer template in the settings, but I am struggling to find examples of how to configure these options th ...

Display the text area when the "Yes" radio button is clicked, while it remains hidden either by default or when the "No" radio button is selected

I am currently working on an html code and I am looking for a way to use java script in order to create a text area box only when the "Yes" radio button is selected. This text area should be hidden by default or when selecting "NO". <table class="tab ...