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

What is the method for producing an li and anchor tag using a list object?

Here is the response I received from my web service, and now I need to transform it into a list item tag: {"d":[{"name":"ttt","url":"bbbb"},{"name":"uuu","url":"ppp"}]} How can I create li tags based on the above output? This is the desired format for t ...

Discovering the unique identifier of an item in Node.js is simple with these steps

I have a delete API which requires the item's unique ID to be passed in for deletion. How can I capture the ID of the item being deleted and send it to the API? Here is the API: app.post("/delete_product", function (req, res) { var data = { ...

Header Express does not contain any cookies, which may vary based on the specific path

In my express.js app, I have two controllers set up for handling requests: /auth and /posts. I've implemented token authorization to set the Authorization cookie, but I'm encountering an issue when making a request to /posts. The request goes th ...

Exploring the Practical Applications of Mutation Types within Vuex

After delving into Vue (2.x) + Vuex for some time, I've noticed a common pattern emerging - the use of Mutation Types. Personally, I find this practice to be unnecessary and only adds complexity to projects with additional files. Perhaps my lack of e ...

A step-by-step guide on retrieving information from Material UI components and incorporating an onSubmit feature to transmit data to the backend server

I've recently started working with react/material-UI. While working on a project, I turned to youtube videos and various resources for guidance. I opted for material-UI due to its user-friendly nature. However, I'm currently facing a challenge ...

Problem with APIGEE search function

Encountered an issue while trying to retrieve an Apigee collection using the following code snippet: var my_pc_list = new Apigee.Collection( { "client":client, "type":"pc_pedidos", qs :{ql:"limit:50"} }); Error details: {"error":"query_parse","timestamp ...

What is the best way to display values from a Localstorage array in a tabular format using a looping structure

I have set up a local storage key 'fsubs' to store form submissions as an array. Here is how I am doing it: var fsubs = JSON.parse(localStorage.getItem('fsubs') || "[]"); var fcodes = {"barcodeno" : this.form.value.barcode, "reelno" : ...

Repairing a syntax error in a jQuery selector variable

$(".className").click(function(){ var link = $(this).find("a").attr('href'); //output is '#myID' var findItems = $(link '.mydiv').length; //WRONG var findItems = $(link + '.mydiv').length; ...

Custom React component - DataGrid

Just starting out in the world of React and attempting to create a custom component with parameters. I'm curious about the correct approach for achieving this. Here's my current code snippet - how do I properly pass Columns, ajax, and datasourc ...

Utilizing a server for seamless communication between a mobile device and a website

Exploring a simple setup idea here: Imagine having a mobile app with a page that contains 4 lines of content (utilizing phonegap for development). The plan is to have a web page where data for those 4 lines can be inputted. Once the information is submitt ...

Create a new JSON file to preserve the value of a JSON object

I am working with a JSON file that looks like this: { "soils": [{ "mukey": "658854", "mukeyName": "Meggett-Kenansville-Garcon-Eunola-Blanton-Bigbee (s1517)", "sl_source": "Fl soil map", "cokey": "3035468", "soilName": "Eunola", " ...

Navigating to a new URL using window.location.href will seamlessly embed the new page within

I am new to JavaScript and I am facing an issue with my AJAX function. The function is supposed to navigate to a new URL, but instead of loading the new page separately as if the user had typed the URL, it gets inserted inside the same div where the button ...

Bringing in the node-spotify or spotify-web modules to the browser for seamless integration

Has anyone successfully used Spotify's Playlist API in a browser? It seems that the web API only covers metadata, and to access the full API I need to use libspotify. Do I need to set up a Spotify API server myself or use node libraries like node-spot ...

Add a CSS class to an innerHTML element just a single time

I currently have 2 files available: data.php page.php The data.php file is responsible for fetching a row from a SQL database and sending it to the page.php file. Within the page.php file, there is a JavaScript script that receives this row through AJAX ...

Troubleshooting Database Saving Problem with Vue.js and Ruby on Rails

Trying to configure a nested form with Vue.js in a Rails application to save ingredients for a recipe. While all other details of the ingredients are saving correctly, the ingredient name (from an input field) is not getting saved in the database. How can ...

Execute Jquery ajax only on the initial invocation

When I am using ajax post in jQuery to build a portion of a page, I am encountering an issue where it only runs once. Below is the code snippet I am working with: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery ...

What is the best way to showcase a div on top of all other elements in an HTML page?

As a newcomer to html and css, I have successfully created a div that contains city names. The issue I am currently facing is when I click on a button to display the div, it gets hidden behind the next section of my page. Take a look at the image below for ...

What is the best way to shorten string values that exceed a certain length?

Here is an array list I have: $myarray = array( array( 'name' => 'File name 1 - type.zip', 'size' => '600KB', ), array( 'name' => 'File name 2 - type.pdf&a ...

Are you interested in creating dynamic tables/models with Sequelize?

Currently, I am exploring a theoretical question before diving into the implementation phase. The scenario is as follows: In my application, users have the ability to upload structured data such as Excel, CSV files, and more. Based on specific requirement ...

Incorporate a line break between the day and month on your JQuery datepicker

Is it possible to insert a line break or some other element between the day and month in the input field when using JQuery datepicker? Here is the current code I have: jQuery('#checkin').datepicker({ showAnim: "drop", dateFormat ...