Yahoo
Yahoo

Reputation: 568

Vue on input text, changes background color for both input fields

I am using bootstrap-vue to display modal. Once the modal is opened using OPEN MODAL BUTTON, it displays two input fields. When I add a text to one of the input field, it changes color on both input fields. Is there a way to change color for the field which consists of datatype only?

View

<div id="app">
  <b-modal id="modal-center" ref="modalRef" centered title="DISPLAY MODAL" v-bind:hide-footer="true">
   <b-row class="my-1">
      <b-col sm="11">
       <div v-for="(listings, index) in list2" :key="index">
        <br/>
        <b-form-input v-model="listings.rfidState1" placeholder="insert text" v-on:input="gotText()" :style="isChanged ? { 'background-color': '#33FF90' } : null" ></b-form-input>
       </div>
      </b-col>
  </b-row>

  <br/>

  <b-row>
    <b-col><b-button block variant="info" v-on:click="hidemodal();">UPDATE</b-button></b-col>
    <br/>
   </b-row>

    <br/>

  </b-modal>

  <b-button block v-b-modal.modal-center variant="info">OPEN MODAL</b-button>

</div>

Script

new Vue({
  el: "#app",
  data: {
    list2: [
      { text: "Learn JavaScript", done: false },
      { text: "Learn Vue", done: false }
    ],

    isChanged: false
  },
  methods: {

    hidemodal(){
        this.$refs['modalRef'].hide()
    },

    gotText(){
        this.isChanged = !this.isChanged;
    }

  }
})

Here is my code on jsfiddle

https://jsfiddle.net/ujjumaki/wgr3m6td/30/

Upvotes: 0

Views: 1590

Answers (1)

Thomas Bay
Thomas Bay

Reputation: 649

Yes this can be done with a few changes.

First, remove isChanged from your data, and add it as a property to each of your list2 objects, so each object looks like this:

{ text: "Your text", done: false, isChanged: false }

next, your :style="isChanged ? ", should instead be:

:style="listings.isChanged ? "

next up, your v-on:input="gotText" should take the index as a parameter like so:

v-on:input="gotText(index)"

last, your gotText method should receive the index and use it to update isChanged:

gotText(index) {
  this.list2[index].isChanged = !this.list2[index].isChanged
}

This should answer your question, but if you want some of the behaviour changed ask away.

Edit: As suggested by n-smits, your data in the vue instance should not be an object, but a function that returns an object like this:

data(){
  return {
    list2: [..]
  }
}

I recommend that you read his comment to understand why this is necessary.

Upvotes: 1

Related Questions