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

Several queries for directions on Google Maps are resulting in the same response being returned for all requests

I've been experimenting with the Google Maps Directions service to retrieve three different travel methods for the same route (driving, walking, and bicycling). Despite successfully iterating through the array of methods and setting them in the respec ...

What is the best way to implement ES2023 functionalities in TypeScript?

I'm facing an issue while trying to utilize the ES2023 toReversed() method in TypeScript within my Next.js project. When building, I encounter the following error: Type error: Property 'toReversed' does not exist on type 'Job[]'. ...

Automatically Access a JS/CSS File in the Developer Tools 'Sources' Section

I am aware that I can customize my own Panel in the Chrome Developer Tools, but I am curious if there is a way to click a button within my panel and have the Developer Tools open a particular script or stylesheet in the 'Sources' panel related to ...

Jasmine is having trouble scrolling the window using executeScript

I usually use the following command: browser.driver.executeScript('window.scrollTo(0,1600);'); However, this command is no longer working. No errors are showing in the console, making it difficult to troubleshoot. Interestingly, the same scri ...

Different results can be observed when comparing the array ordering in JavaScript between IE8 and Chrome

The array presented with items listed in specific order: { "5":{ "Title":"Title A", "Desc":"Description A" }, "15":{ "Title":"Title B", "Desc":"Description B" }, "10":{ "Title":"Title C", "Desc":"Description C ...

The Datatable is only displaying a single record

After fetching data from a firestore collection and storing them in an array, I encountered an issue where only one entry is displayed in the datatable despite retrieving all documents from the firestore collection. What could be causing this problem? Belo ...

Identify the CSS class for the ionic component on the webpage

Currently, I am in the process of developing an application using ionic 2 and angular 2. Within this app, I am utilizing the ionic 2 component known as ModalController. Unfortunately, I have encountered a challenge when attempting to adjust the size of th ...

React - The content of my JSON.String vanishes upon being placed inside a div element

My NFTDetails component includes a description from a JSON, which contains \n\n in it. Strangely, there are no new lines when I render the JSON value in a div, but when I log it to the console in Firefox, new lines appear. How can I make use of ...

Guide to converting an arraylist of custom objects into JSON using JavaScript

I have a List returned to the jag. It is of type (java.util.List) and I need to print it as a json. var storeForum = Packages.org.wso2.carbon.forum.registry.RegistryForumManager; var forum = new storeForum(); var start = request.getParameter(&a ...

Tips for accessing user-defined headers within CORS middleware

I've developed a CORS middleware utilizing the CORS package. This middleware is invoked before each request. Here's how I implemented it: const corsMiddleware = async (req, callback) => { const { userid } = req.headers|| req.cookies {}; l ...

Implementing Dynamic Script Injection in Angular Controllers for Enhanced HTML Functionality

I'm a total beginner when it comes to Angular and frontend development, so please bear with me if my question seems basic: In my controller, I have the following code where I am populating the $window.user data that is being used in the script [2] ad ...

Implementing the expand and collapse functionality to the Discovery sidebar on the DSpace 4.2 xmlui platform

I recently began using DSpace and I am attempting to implement an expand/collapse feature in the Discovery sidebar of DSpace 4.2 xmlui using the Mirage theme. After finding some helpful jquery code, I attempted to add this functionality by placing the js f ...

My WordPress loadmore function is not providing any additional posts

Hey everyone, I'm facing a Wordpress issue that I can't seem to resolve. I've checked other posts but haven't found the solution yet. So, I decided to share my code here and seek help. My problem is with trying to load more posts using ...

JS Function created to supply elements to React component is failing to return correctly

Trying to validate a dataset by checking for specific prefixes or suffixes in a string, and then breaking the string into <span> elements. The current function correctly identifies the relevant morphemes in the data set, but fails to return the split ...

forEach`` binding in knockout object

data:[ "properties": {"CountryName": "qwerty", "Population":"785004"} ] features:[ "properties": {"LastName": "abc"} ] .... Retrieving information from a JavaScript object called data and storing it in another. resultData = ...

error": "Unable to access undefined properties (reading 'SecretString')

Encountering the error message Cannot read properties of undefined (reading 'SecretString') when utilizing @aws-sdk/client-secrets-manager? It's a sign that you should consider updating your code to accommodate the latest version. ...

Animating slides with CSS Keyframes and React, incorporating toggle slide fade out and slide fade (back) in

I am seeking a solution for toggling a box (div) with slide-out animation and then sliding back in animation (in reverse) upon button press. My requirement is to have no animations during the initial page render. While I can successfully slide the box to ...

Error encountered in jsonwebtoken payload

Working on a web application with nodejs and angular cli, I have implemented JWT for login authentication. However, during the processing, I encountered the following error: Error: Expected "payload" to be a plain object. at validate (D:\Mean ...

Is the 404 error a result of the ajax code?

I'm currently working on a form that utilizes AJAX to validate and interconnect various form elements. Below is a simplified version of my code: <?php if( isset( $_POST['create_transaction'] ) ) { // do something } ?> <div> ...

Issue with OBJLoader showing a blank screen

Does anyone have experience with rendering OBJ files using three.js? I'm having trouble getting them to display on the screen and would appreciate any help or advice. The strange thing is that a simple cube renders perfectly in my project. For those ...