Modify the background color based on the length of the input in Vue

Can you change the background color of the initial input field to green if the value of the Fullname input field is greater than 3 characters?

See below for the code:

<div id="app">
  <input type="text" v-model="fullname" placeholder="Enter Full Name" @input="changeInitialColor"/>
  <input type="text" v-model="initial" placeholder="On Full Name make it green"/>
</div>

Please find the JavaScript code snippet:

new Vue({
  el: "#app",
  data: {
    fullname:'',
    inital:''
  },
  methods: {
    changeInitialColor(){
     if(this.fullname.length > 3){
      console.log('Change v-model=Initial field color into green');
     }
     else{
      console.log("Dont change color");
     }
    }
  }
})

You can also access the code on JSFIDDLE:

https://jsfiddle.net/ujjumaki/kya27g9w/1/

Answer №1

To implement this functionality, you can utilize a computed property along with css class bindings

<input type="text" v-model="fullname" placeholder="Enter Full Name"/>
<input type="text" v-model="initial" :class="{ green: fullnameIsMoreThan3Chars }"/>

// --
,methods: { ... }
,computed: {
    fullnameIsMoreThan3Chars(){
        return this.fullname.length > 3;
    }
}

Answer №2

To apply conditional styling based on the length of a variable, you can use either style or class binding. Here is an example using style binding:

style="{'background-color': fullname.length > 3 ? 'green' : ''}"

<input type="text" v-model="initial"
 style="{'background-color': fullname.length > 3 ? 'green' : ''}" 
placeholder="If Full Name has more than 3 characters, the background will be green"/>

Answer №3

If you want to dynamically add a class to an input based on the length of the full name, you can use a class binding in Vue.js.

<input type="text" v-model="initial" placeholder="If Full Name is more than 3 characters, it turns green" :class="{'green': fullname.length > 3}"/>

Alternatively, you can create a computed property to determine if the full name input has more than three characters and then use this computed value as the class instead (which can help keep your template cleaner).

<input type="text" v-model="initial" placeholder="If Full Name is more than 3 characters, it turns green" :class="{'green': fullNameOk}"/>

{
  ...
  computed: {
    fullNameOk() {
      return this.fullname.length > 3
    }
  }
}

Feel free to check out the working fiddle for reference.

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

Error: React unable to locate module './WebpackMissingModule'

Recently I started diving into React, and I'm encountering some difficulties trying to export components. Here is my current index.js file setup: import React from 'react'; import ReactDOM from 'react-dom'; import SearchBar from ...

What causes the initial AJAX response to be delayed by 10 seconds when using setInterval()?

I have a task that requires me to send an ajax request to display an image that changes every 10 seconds. However, I'm encountering an issue where my webpage remains blank for the first 10 seconds and only displays the first image after the initial de ...

Ensuring Proper Tabulator Width Adjustment Across All Browser Zoom Levels

<div id="wormGearTabulatorTable" style="max-height: 100%; max-width: 100%; position: relative;" class="tabulator" role="grid" tabulator-layout="fitDataTable"><div class="tabulator-header" role="rowgroup"><div class="tabulator-header-co ...

Retrieve specific components of objects using a GET request

When visitors land on my web app's homepage, a GET request is triggered to fetch a current list of Stadiums stored in the database through my API. However, the Stadium objects retrieved are packed with unnecessary data, particularly extensive arrays o ...

Would it be unwise to create a link to a database directly from the client?

If I want to connect my React app to Snowflake all client-side, are there any potential issues? This web app is not public-facing and can only be accessed by being part of our VPN network. I came across this Stack Overflow discussion about making API cal ...

Develop a JavaScript library for use in the npm ecosystem

I have developed a minimalist JavaScript library that includes common functions: !!window.JsUtils || (window.JsUtils = {}); JsUtils = (function () { "use strict"; return { randomHex: function (len) { var maxlen = 8; ...

Dynamic row Material-UI input field

Is there a way to create a multiline TextField component that expands to take full height on different devices? I am familiar with fullWidth, but is there an equivalent for setting the height of the component to full on rows depending on the device it is ...

Unable to retrieve the store's vuex state

Below is the main file path /main.js import Vue from 'vue'; import App from './App.vue'; import vuetify from './plugins/vuetify'; import router from './router'; import store from './store/index.js'; Vue.c ...

Looking to display a div with a unique timer?

Is there a way to display different divs with unique classes for specific durations of time? For example, I want one div to show for 2000 ms with the class 'one', then another div to show for 4000 ms with the class 'two', followed by a ...

The background color spills outside the column when using 100% width

Bootstrap 5 is being used, and two columns have been created on the page. The current output looks like this: https://i.stack.imgur.com/P6oZs.png Now, there's a need to display an orange color from end to end of the left column. To achieve this, h- ...

The type 'Navigator' does not have the property 'userAgentData' in its definition

Since I'm looking to minimize the information provided by navigator.userAgent, I decided to migrate to User-Agent Client Hints. However, I've encountered an error while attempting to do so: https://i.stack.imgur.com/lgIl7.png Could someone plea ...

ways to conceal icon image when the textbox is devoid of content

Is there a way to hide the clear icon from a text box if the length inside the text box is less than 1? I attempted the following code, but it didn't work for me. The inner icon is not hidden when the input field length is less than 1. For a demo ex ...

Utilizing React Typescript Discriminating Unions to choose between two different types based solely on props

In my project, I have a component that consists of different types: type Base = { color: string } type Button = { to: string } & Base type Link = { link: string linkNewTab: boolean } & Base type ComponentProps = Button | Link e ...

The Tab style in Mobile Angular UI does not get applied correctly when nested within an ng-repear

While working on a tabbed control with mobile-angular-ui (), I encountered an issue when trying to generate the tabs dynamically. Initially, everything looked good with the following code: <ul class="nav nav-tabs" ui-state='activeTab' ui-def ...

What methods can I use to ensure that a user's credentials are not shown in the URL?

My NextJS application sometimes behaves unexpectedly. Whenever I have a slow connection and the initial load time of the site is longer than usual, after trying to log in to the application, the credentials I entered are displayed in the URL. This happens ...

Tips for increasing the width of a button within an HTML table heading

I'm attempting to make a button within a table <th> expand to the full width and height of the header column, even if a table cell in the same column is larger than the text. If I set the width to 100% in CSS, the button ends up matching the siz ...

Is there a way to modify the displayed value of json_encode() with jQuery?

I am using the json_encode() function to insert data into the database. How can I retrieve just the values of name_units from the units row in the database? This is how the output looks like in PHP code (generated by json_encode()): my_table=>units=>nam ...

Storing an array within an AngularJS service for better performance

As someone who is relatively new to AngularJS, I am still in the process of understanding how to utilize services for fetching data in my application. My aim here is to find a method to store the output of a $http.get() call that returns a JSON array. In ...

Challenges encountered while attempting to animate the CSS clip feature in WebKit

I've been searching everywhere for a solution to my issue, but none of them seem to work. As someone new to CSS3 Animations, I appreciate your patience. I created a simple animation using CSS3 that functions perfectly in IE and Firefox, however, it ...

Is it possible to use cakephp and AJAX to determine if a table is empty?

Is there a way to determine if a table is empty using CakePHP and AJAX? In my index.ctp, I have included an image that, when clicked, will notify the user about the status of the table. If the table is empty, an alert box will pop up; otherwise, the user w ...