spirito_libero
spirito_libero

Reputation: 1332

VueJS change border color of the input if input is already filled in

I need to change the border color of the input if the customer already filled in the field.

How can I do this using VueJS ?

<div class="some-basic-div", '@change' => 'checkForInput'>
  <div class="dc-form-group ">
   <input type='text' id='first_name' >
  </div>
  <div class="dc-form-group ">
    <input type='text' id='last_name' >
  </div>
  <div class="dc-form-group ">
    <input type='text' id='some_text' >
  </div>
</end>

I have tried to use pure JavaScript.

 checkForInput: function(e) {
    let targetDiv = event.target;

    if (targetDiv.value == "") {
      targetDiv.classList.remove("mod-group-success");
    } else {
      targetDiv.classList.add("mod-group-success") ;
    }
  }

So when I am changing the input I need to change the style of the input which I filled in.

Upvotes: 1

Views: 11509

Answers (2)

Sphinx
Sphinx

Reputation: 10729

Uses Class & Styles binding,

below is one simple demo for class binding.

Vue.config.productionTip = false
app = new Vue({
  el: "#app",
  data: {
    testValue: ''
  },
  computed: {
    computedInputStyleEnable: function () { // or use one method instead of computed property
      //apply your own logic at here to determinate if enable input-has-value-style
      return this.testValue && this.testValue.length > 0
    }
  },
  methods: {
    applyInputStyle: function (targetInput) { // bind with one method and return Array
      return [targetInput && targetInput.length > 0 ? 'input-has-value-style' : 'input-no-value-style']
    }
  }
})
.input-has-value-style {
  border: 2px solid green;
  background-color:lightgreen;
}

.input-no-value-style {
  border: 2px solid red;
  background-color:pink;
}
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
  <div>
    <p>Already filled in {{testValue.length}} characters.</p>
    <input type='text' v-model="testValue"
     :class="{'input-has-value-style': computedInputStyleEnable}"
    />
  </div>
  <div>
    <p>Already filled in {{testValue.length}} characters.</p>
    <input type='text' v-model="testValue"
     :class="applyInputStyle(testValue)"
    />
  </div>
</div>

Upvotes: 1

spirito_libero
spirito_libero

Reputation: 1332

I've wrote this code for handling the issue:

Vue.config.productionTip = false
app = new Vue({
 el: "#app",
 data: {
  testValue: ''
 }
},
  methods: {
    checkForInput: function(e){
      let input = event.target
      if (input.value != "") {
        input.classList.add("mod-group-success") ;
      } else {
        input.classList.remove("mod-group-success");
      }
    }
  }
})

And putted on front end:

'@change' => 'checkForInput'

Upvotes: 1

Related Questions