0

Code consists of two input field , if the value of the Fullname is greater than 3, then its suppose to change the initial input field background into green. Is there a way to do that ?

View

<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>

Script

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");
     }
    }
  }
})

Below is the code on JSFIDDLE

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

3 Answers 3

1

one way would be to use a computed property 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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You could use style or class binding like :

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

 <input type="text" v-model="initial"
 style="{'background-color':fullname.length>3?'green':''}" 
placeholder="On Full Name make it green"/>

Comments

1

You can do a class binding to conditionally add a class to initial based on the length of the fullname input.

<input type="text" v-model="initial" placeholder="On Full Name makes it green" :class="{'green': fullname.length > 3}"/>

You can also create a computed property to know if the fullname input is greater than three and use that computed value instead (should keep your template cleaner)

<input type="text" v-model="initial" placeholder="On Full Name makes it green" :class="{'green': fullNameOk}"/>

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

Here's a working fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.