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

Having an absolute element can lead to overflow causing a scroll

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> .wrap { ...

Using assets in data property or methods in Vue 3 with Vite - how to efficiently manage and access resources

Recently delving into Vue 3 and vite, I've encountered a peculiar issue during production build. In development, everything runs smoothly but when I switch to production, the assets defined in the data property are inexplicably ignored, leading to a 4 ...

Trigger a popup using the javascript .link() method

I am currently using ag-grid to present JSON data. When the values are located within nested objects, I have to utilize a valueGetter from the grid API to map to the appropriate value. The value getter returns a value for each row and the grid matches it t ...

Automatically switch to dark mode at specified times: A simple guide

Here is the current method for toggling themes: let themeToggler = document.getElementById('theme-toggler'); themeToggler.onclick = () => { themeToggler.classList.toggle('fa-sun'); if (themeToggler.classList.contains('f ...

Aggregating MongoDB: Calculating unique values within an array

Looking to find the distinct tags count on all records within a mongodb query, utilizing JS. Data structure of the record: { "_id": { "$oid": "62e593aed8fd9808777225e8" }, "title": "β€œThe world as ...

Tips for concealing one modal and revealing a different one upon page refresh

I am facing an issue with my modal form. What I want is for the modal to close upon submitting the form, then for the page to reload, and finally for the success modal to be displayed. However, when I clicked submit, the success modal ended up appearing o ...

Having trouble using $.post in jQuery AJAX with the .click() method?

I am experiencing some issues with my ajax request. It appears that the $.post method is not functioning as expected, as no request is being sent. There is also no information showing up in Firebug. Interestingly, I can make this code work: $('.c ...

Combining column values with AngularJS

What is the best way to merge column values in AngularJS? ...

I am utilizing jQuery's AJAX function with a datatype of HTML to extract a specific portion of the incoming data

This is the JavaScript function I am working with: function getCountryRegions() { var postData = "id="+$("#selectedCountryId").val(); $.ajax({ url:"/region", data: postData, dataType:"html", type:"POST", ...

Obtaining environmental variables from the environment in a Vite project's GitHub Actions .yaml file

I'm looking to define an environment variable within a GitHub Action .yaml file that can be accessed in my Vite project at runtime. Example: # staging.yaml - GitHub Action file ... env: VITE_INTERNAL = true ... // index.vue - My Vite project function ...

"What is the best approach to adjusting the width of one div based on the width of another div using CSS Grid

As a beginner in programming, I'm trying to work with CSS Grid but facing some challenges. My goal is to create a component with two columns: the left column should have a width of minmax(570px, 720px), and the right column should be minmax(380px, 10 ...

Tips for dynamically expanding the interface or type of an object in TypeScript

Currently, I am exploring the integration of PayPal's Glamorous CSS-in-JS library into a boilerplate project that also utilizes TypeScript. Glamorous provides a way to incorporate props into an element as shown below: const Section = glamorous.secti ...

Upcoming topics - The Challenge of Staying Hydrated at Basecamp One

I have implemented a themes package for dark mode and light mode in my project. Despite doing the installation correctly as per the repository instructions, I am encountering an issue. My expected behavior for the project is: The webpage should initially ...

What is the best way to display all divs once more after all filter-checkboxes have been unchecked?

I created a custom filter that displays board games based on the number of players and playing time selected through checkboxes. Initially, the filter works as intended when first loaded and used. However, I encountered an issue where if all checkboxes are ...

Adjust the background color of JQuery UI modal dialog overlay in real-time

How can I dynamically change the background color of a page when a modal dialog loads, specifically targeting only one specific modal dialog? Setting the background color with CSS works fine: .ui-widget-overlay { background-color: white; } Here's ...

HTML Navigator encountering Javascript Anomaly

Here is the code snippet I'm working with: driver = new HtmlUnitDriver(); ((HtmlUnitDriver) driver).setJavascriptEnabled(true); baseUrl = "http://www.url.com/"; driver.get(baseUrl + "/"); ... However, whenever I ...

Why doesn't the z-index of child elements function properly when their fixed parents share the same z-index value?

I have utilized jsfiddle to replicate my problem. My goal is to position .top .inside above .bottom .inside. I am aware that z-index only functions within its respective position type, for example fixed and absolute do not share the same z-index level. How ...

Is there a way to create a pixelated render target using THREE JS?

Attempting to set up a basic render target where I render one scene and then use it as a texture over a quad. The demo seems to be pixelated when running, almost like it's rendered on a small screen and stretched across the quad. Below is the code sn ...

Error occurred while looking for user by ID in the everyauth

I previously had a working example with express 2.*, but now I am transitioning to version 3.*. The issue arises during authentication with Facebook, causing some problems. Everything works fine until everyauth makes the GET request to Facebook and then re ...

Setting up JavaScript imports in Next.js may seem tricky at first, but with

Whenever I run the command npx create-next-app, a prompt appears asking me to specify an import alias. This question includes options such as ( * / ** ) that I find confusing. My preference is to use standard ES6 import statements, like this: import Nav f ...