Modifying the content in one form field based on the information entered in another input field

I have a scheduling application that includes a form for selecting both the departure city and arrival city. The app is designed for international travel only, so when a user selects a city from Hungary as the departure city, I want to exclude all Hungarian cities from the list of recommended arrival cities in the next input field. To access the database, I am using axios and the application itself was created with NuxtJs.

How can I populate the second input field with all cities except those belonging to the country of the selected departure city?

Below is the code snippet for the dropdown lists in the inputs:

<template>
  <div class="dropdownList">
    <label class="formLabel">{{ label }}</label>

    <input
      ref="dropdowninput"
      v-if="Object.keys(selectedItem).length === 0"
      v-model.trim="inputValue"
      class="dropdown-input"
      type="text"
      :placeholder="placeholder"
    />

    <div v-else @click="resetItem" class="dropdown-selected">
      {{ selectedItem.name }}
    </div>

    <div v-show="inputValue && apiLoaded" class="dropdown-list">
      <div
        @click="selectItem(item)"
        v-show="itemVisible(item)"
        v-for="item in itemList"
        :key="item.name"
        class="dropdown-item"
      >
        {{ item.name }}
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      selectedItem: {},
      inputValue: "",
      itemList: [],
      apiLoaded: false,
      apiUrl:
        "***"
    };
  },
  props: ["placeholder", "label"],

  mounted() {
    this.getList();
    this.filteredCities();
  },

  methods: {
    filteredCities() {
      let filtered = this.itemList.filter(res => res.countryCode != "ro");
      return filtered;
    },
    getList() {
      axios.get(this.apiUrl).then(response => {
        this.itemList = response.data;
        this.apiLoaded = true;
      });
    },

    itemVisible(item) {
      let currentName = item.name.toLowerCase();
      let currentInput = this.inputValue.toLowerCase();
      return currentName.includes(currentInput);
    },
    selectItem(theItem) {
      this.selectedItem = theItem;
      this.inputValue = "";
      this.$emit("on-item-selected", theItem);
    },
    resetItem() {
      this.selectedItem = {};
      this.$nextTick(() => this.$refs.dropdowninput.focus());
      this.$emit("on-item-reset");
    }
  }
};
</script>

The data stored in my database resembles the following structure:

Answer №1

This approach simplifies the process of dynamically fetching data from an API using a variable stored in the parent component's input.

test.vue (a page)

<template>
  <div>
    <p>Enter 'todos', 'albums', or 'photos' to see corresponding data (note: 'photos' query is more extensive)</p>
    <input v-model.lazy.trim="selectedEntity" type="text" style="border: 2px solid hsl(0, 100%, 50%)" />
    <br />
    <br />

    <child :selected-entity="selectedEntity"></child>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedEntity: '',
    }
  },
}
</script>

Child.vue (component)

<template>
  <div>
    <p>Displaying all available results:</p>
    <hr />
    <div v-for="result in results" :key="result.id">
      {{ result.title }}
    </div>
  </div>
</template>

<script>
export default {
  props: {
    selectedEntity: {
      type: String,
      default: 'todos',
    },
  },
  data() {
    return {
      results: [],
    }
  },
  async fetch() {
    this.results = await this.$axios.$get(`https://jsonplaceholder.typicode.com/${this.selectedEntity}`)
  },
  watch: {
    async selectedEntity(newValue) {
      console.log('newValue >>', newValue)
      await this.$fetch()
    },
  },
}
</script>

The data fetch is triggered on the change event when you enter text in the input field and then click outside it (this can be improved).

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

Sending the factory's response back to the controller in AngularJS

I operate a factory that uses an api call to request user data: angular.module('MyApp') .factory('UserApi', function($auth,Account){ return { getProfile: function() { Account.get ...

Element not chosen in Angular version 6

Recently delving into Angular 6, I've been working on setting up form validation within an Angular form. Validation has been successfully implemented, but there's a minor issue with the select box displaying an empty first value. Here is my code ...

Getting rid of unwanted scrollbars in a breeze

I am facing an issue with two nested divs that have the same height settings. The outer div has a max-width/height constraint along with overflow auto, causing scrollbars to appear when the inner content exceeds its dimensions. However, even if I resize ...

Tips for resolving the Error: Hydration issue in my code due to the initial UI not matching what was rendered on the server

export default function Page({ data1 }) { const [bookmark, setBookmark] = useState( typeof window !== 'undefined' ? JSON.parse(localStorage.getItem('bookmark')) : [] ); const addToBookmark = (ayatLs) => { s ...

Updates to a Vue 3 component's UI are not reflected when the props are changed

My goal is to ensure that my child component updates when props are changed. However, this doesn't seem to be happening as expected: // App.vue <template> <div id="app"> <Foo :foo="foo" /> ...

Looking to replicate a Modal that I designed, but unsure which elements need altering in order to achieve this. I am hoping to create three duplicates of the Modal

This modal is functioning perfectly, and now I want to replicate the same modal three times on a single page. I require three distinct buttons on the same page to trigger these separate modals. At this point, I am unsure which attributes need modification ...

Custom Vue Basic String Renderer for JSONForms

I'm delving into Vue JSONForms and attempting to develop a basic custom text renderer from scratch. While I am aware of the vue-vanilla package available in JSONForms, I want to grasp the fundamental requirements for creating a custom renderer as I an ...

Can you explain the key distinction between the backtick (`) and the ampersand-hash-39

I am completely new to TypeScript, JavaScript, and Angular. As I follow some tutorials, I often encounter code snippets like the one below: class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return `(${this.x}, ${th ...

How can we stop the constant fluctuation of the last number on a number input field with a maxLength restriction

In my ReactJS code, I have an input field that looks like this: <input type="number" onKeyPress={handleKeyPress} maxLength={3} min="0" max="999" step=".1" onPaste={handlePaste} /> Below are the functions associated w ...

Struggling to get my upload form to function properly with two different versions of jQuery, even after attempting to use jQuery.noConflict

I am facing an issue with a webpage that contains two different forms. The first form is for uploading pictures and generating the link for the uploaded images, while the second form is a regular one used to add products to a database using the links from ...

An error occurred while trying to serialize the `.res` response received from the `getServerSideProps` function in

I encountered the following issue while utilizing the getServerSideProps function to fetch data from Binance API. import binance from "../config/binance-config"; export async function getServerSideProps() { const res = await binance.balance(( ...

Tips for enforcing a new line for each attribute in Vue using Prettier within the VS Code environment

I am currently using Prettier Version: 9.5.0 for Vue in VSCode. This is the code snippet I'm working with: <q-select label="Fruits" :options="['apple', 'mango']" /> This is how I want Prettier to format ...

I keep encountering the same issue every time I try to execute the npm run watch command. Does anyone have any suggestions on how to fix this?

When attempting to execute the command npm run watch, I encountered an error as shown below: ERROR Failed to compile with 1 errors2:50:28 PM This dependency was not found: * vue in ./resources/js/app.js To install it, you can run: npm install --save vue ...

Dynamically load modules within an AngularJS application

Is there a way to dynamically load module scripts? I have 2 JS files: module1.js (function() { var mod = angular.module('module1', []); .... })(); This is the second one: module2.js (function() { var mod = angular.module('m ...

react component not displaying image

I must admit, this might be a silly question but I'm just starting out in web development. My goal is to create a clickable image component that redirects to another page on the website. However, despite not encountering any errors, the image is not ...

Is it possible to retrieve AJAX data through a callback function?

I have encountered an issue where the ajax success function does not return data as expected. I attempted to use a callback function instead, but I still end up with undefined results. I resorted to using the variable responseText, however, I am looking fo ...

How to integrate MDB Vue into your Laravel 5.8 project

I've been trying to integrate MDB Vue into my fresh Laravel application using npm, but I'm facing some challenges. Here's what I've done so far: 1. Created a new Laravel app 2. Navigated to the directory www/myApp 3. Ran npm install 4 ...

Encountering an Issue with NPM Run Production in PostCSS

I keep encountering the same error whenever I attempt to execute 'npm run production'. The remainder of the error consists of a compilation of 'node_modules' packages where this issue is also present. ERROR in ./resources/assets/sass/ap ...

What is the best way to store React form data in a queue for future processing?

I am currently developing a ticketing system in React, utilizing Node.js for the backend and Python for the email server. My goal is to process form submissions by extracting all the form data, creating an instance of a plain JavaScript class with only a ...

Using Angular 4: Redirecting Menu to Component with Electron

I am currently working on my first project using Angular 4 and Electron to develop a desktop application. One of the challenges I'm facing is figuring out how to redirect to a specific component when a submenu item is clicked after overriding the ele ...