1

In my Vue component I have a form with two select inputs. I also have a button where I want to make it possible that when you click on it, both selected values switch with each other.

My form:

<v-form
  class="form"
  @submit.prevent="submitRequest"
  >
    <v-col class="d-flex" xs="12" sm="12" md="12" lg="12">
        <v-select
            v-model="form.fromCity"
            name="fromCity"
            required
            :items="form.selectItems"
            item-text="mediumName"
            item-value="uicCode"
            label="From city"
            solo
            autofocus
        ></v-select>

        <v-btn text small color="primary" @click="switchValues()">
            <v-icon>fa-exchange-alt</v-icon>
        </v-btn>

        <v-select
            v-model="form.toCity"
            name="toCity"
            required
            :items="form.selectItems"
            item-text="mediumName"
            item-value="uicCode"
            label="To city"
            solo
            return-object
        ></v-select>
    </v-col>

    <v-col class="d-flex" xs="12" sm="12" md="6" lg="3">
        <v-btn 
        color="primary"
        type="submit"
        >Choose</v-btn>
    </v-col>
  </v-form> 

Where I set the properties:

   data: () =>  ({
        form: {
            selectItems: [
                {'uicCode': '8400206', 'mediumName' : 'Eindhoven'},
                {'uicCode': '8400597', 'mediumName' : 'Tilburg'},
            ],
            fromCity: '',
            toCity: ''
        },
    })

I tried this, but obviously this doesn't work:

   switchValues() {
        this.form.fromCity = this.form.toCity
        this.form.toCity = this.form.toCity
    }

My question is, how can I switch the selected inputs without messing it up like I just did? Is there an easy way to just grab the value of each input and switch it over?

1 Answer 1

1

You just need to swap the values from city and to city:

Just rewrite the switchValues method

switchValues() {
      const temp = this.form.fromCity;
      this.form.fromCity = this.form.toCity
      this.form.toCity = temp;
    }

Add return-object property to fromCity select box

Working codepen here: https://codepen.io/chansv/pen/KKKvrom?editors=1010

Sign up to request clarification or add additional context in comments.

3 Comments

do upvote and accept this answer, if this resolves your issue..Thanks
The switching works, thanks. But now the values aren't correct anymore because the item-value uicCode from selectItems isn't switched. Any idea on how I can fix this? Should I swap between selectItems instead of fromCity / toCity properties?
I've updated codepen, add return-object to fromCity as well

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.