"Utilizing Vue.js to dynamically fill input fields based on the selection of an element

As I am still new to learning Vue.js, I may not be using the correct terminology here. My current project involves a basic Vue application where I have implemented a simple search box functionality.

The search box triggers an event (v-on:blur) when text is inputted, which then calls a function to display suggestions right below the search box.

What I want to accomplish is that when any of the anchor tags in the search suggestions are clicked, two new input boxes should automatically populate with the values from the suggestions.

{name: 'Some Name', state: 'Some State'}

You can find a minimalistic version of the code on this link.

new Vue({
  el: "#app",
  data: {
    suggestions: [],
    showSuggestions: false,
  },
  methods: {
    suggest() {
      // these suggestions are dynamically generated via ajax
      this.suggestions = [{
          name: 'A',
          state: 'OH'
        },
        {
          name: 'B',
          state: 'OR'
        },
      ];
      this.showSuggestions = true;
    }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input type="text" v-on:blur="suggest" placeholder="search">
  <div v-show="showSuggestions">
    <span>Did you mean</span>
    <li v-for="s in suggestions">
      <a href="#">
        {{s.name}} - ({{s.state}})
      </a>
    </li>
  </div>
  <input type="text" name="name" placeholder="name">
  <input type="text" name="state" placeholder="state">
</div>

Answer №1

To easily input values into your name and state fields, it is recommended to utilize v-model on them along with declaring the corresponding data in your component. This enables you to easily assign values using this.name and this.state:

data: {
  suggestions: [],
  showSuggestions: false,
  name: '',
  state: ''
},

Make use of v-model to connect name and state data to your input elements:

<input type="text" name="name" placeholder="name" v-model="name">
<input type="text" name="state" placeholder="state" v-model="state">

You can attach a click handler to each <a> element so that you can pass the index of the clicked suggestion. By doing this, you will be able to access the data by referring to this.suggestion[i]:

<li v-for="(s, i) in suggestions" v-bind:key="i">
  <a href="#" v-on:click.prevent="suggestionSelected(i)">
    {{s.name}} - ({{s.state}})
  </a>
</li>

In your methods, create a new function called suggestionSelected, which takes the index of the selected suggestion as i. This allows you to retrieve the selected suggestion using bracket syntax:

suggestionSelected(i) {
  this.name = this.suggestions[i].name;
  this.state = this.suggestions[i].state;
}

Below is a proof-of-concept example:

new Vue({
  el: "#app",
  data: {
    suggestions: [],
    showSuggestions: false,
    name: '',
    state: ''
  },
  methods: {
    suggest() {
      // Dynamic data fetched via ajax
      this.suggestions = [{
          name: 'A',
          state: 'OH'
        },
        {
          name: 'B',
          state: 'OR'
        },
      ];

      this.showSuggestions = true;
    },
    suggestionSelected(i) {
      this.name = this.suggestions[i].name;
      this.state = this.suggestions[i].state;
    }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input type="text" v-on:blur="suggest" placeholder="search">
  <div v-show="showSuggestions">
    <span>Did you mean</span>
    <li v-for="(s, i) in suggestions" v-bind:key="i">
      <a href="#" v-on:click.prevent="suggestionSelected(i)">
        {{s.name}} - ({{s.state}})
      </a>
    </li>
  </div>
  <input type="text" name="name" placeholder="name" v-model="name">
  <input type="text" name="state" placeholder="state" v-model="state">

</div>

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

The JQuery JavaScript function fails to complete its execution

Question: How can I resolve the issue where my PHP file returns a large JSON string with approximately 2000 elements, each having 14 child elements? When using jQuery AJAX to fetch the JSON and populate an ID-identified table, the filling process stops mid ...

Unable to access the .env file in Vue.js when executing cross-env NODE_ENV=development webpack-dev-server --open --hot

I'm attempting to utilize an .env file for storing local variables, but I am encountering an issue where they appear as undefined when I try to log them. Here is a snippet from my .env file (located at the root of my project): VUE_APP_STRAPI_HOST=htt ...

Using the spread operator in React to distribute JSX elements within a map function

I am struggling with mapping over an array within another array to create a Picker and am having difficulty returning JSX elements instead of an array of JSX elements. Here is the code example: {modelA.map((mA) => { const pickerItems = mA.modelB.m ...

In MUI v5 React, the scroll bar vanishes from view when the drawer is open

Currently, I am working on developing a responsive drawer in React using mui v5. In the set-up, the minimum width of the drawer is defined as 600px when it expands to full width. However, an issue arises when the screen exceeds 600px - at this point, the d ...

Tips for combining values from two inputs to an angular ng-model in AngularJS

I am working with an angular application and I am trying to figure out how to combine values from multiple inputs into one ng-model. Here is an example of my current input: <input type="text" class="form-control input-md" name="type" ng-model="flat.f ...

Can you explain the syntax for the Javascript tag?

While browsing through some code, I stumbled upon this snippet and found myself puzzled by the not:. Is it a tag of some sort? And if so, are there alternative applications for it? var foo = { not: function(bool) { return !bool; } } I'm curious t ...

HTMLElement addition assignment failing due to whitespace issues

My current challenge involves adding letters to a HTMLElement one by one, but I'm noticing that whitespace disappears in the process. Here's an example: let s = "f o o b a r"; let e = document.createElement('span'); for (let i ...

Transform nested properties of an object into a new data type

I created a versatile function that recursively converts nested property values into numbers: type CastToNumber<T> = T extends string ? number : { [K in keyof T]: CastToNumber<T[K]> }; type StringMap = { [key: string]: any }; const castOb ...

How can I position an object in Three.js to perfectly align with the left half of the screen, adjusting both its width

When the button is clicked, I want the entire 3D object's width and height to adjust to fit on the left side of the screen, while displaying a div HTML info on the right side. How can I make the object fit on the left side of the screen? Can I use ma ...

The innerHTML of null cannot be set in Vue JS

I am attempting to showcase my array and its modifications after applying various methods <template> <div> <div id="example"></div> <div id="example1"></div> </div> </template> <s ...

Using an external call to trigger the revert method in jQuery UI

My draggable event setup looks like this: $(ids.label).draggable({ containment: ids.wrapper, revertDuration: 100, revert: function(event) { $(this).data("draggable").originalPosition = { top: $(this).data('origionalTo ...

Performing a Jquery ajax post to an MVC2 action

I have a script set up to send a POST request to an endpoint, and it seems like the routing is correct as it hits the breakpoint on the server. $(document).ready(function() { var o = new Object(); o.message = 'Hi from the page'; $.ajax({ ...

Navigate back to the previous page following the completion of an AJAX data submission

When using ajax to send data from page A to the server, the spring controller returns welcome page B. This process works correctly on Firefox and Internet Explorer, but on Chrome, there is an issue where after successfully sending the data via ajax, the de ...

An issue arose when attempting to run vue-cli-service build or npm run build on a shared hosting platform, resulting in an error related

Encountering an error when attempting to build my Vue project on a shared hosting service: Interestingly, running npm run build on my local environment results in success. Error Description: Building for production.../home/intechpe/onlineku-admin/n ...

Using AngularJS Scope to Map an Array within a JSON Array

I'm attempting to extract the type and url values from the media2 object within this JSON array and assign them to an AngularJS scope Array. "results":[ { "session2":[ { "__type":"Object", "abou ...

Guide on Sending a POST Request via HTTPS in Websites

I am developing a browser extension for Chrome that requires sending a post request to a server using standard HTTP. However, this is causing a mixed content error when I'm on a website that uses HTTPS, and the browser refuses to process my request. ...

Changing the background color of a PHP input based on the webpage being viewed - here's how!

I'm in the process of creating a website where each page will have its own unique background color. Additionally, I am using a PHP input for both the header and footer sections, which need to change their background colors based on the specific webpa ...

Switch Between Different Background Colors for Table Rows With Each Click

This script changes colors when a row in a specific column is clicked: $(document).ready(function(){ $("#rowClick").children("tbody").children("tr").children("td").click(function(){ $(this.parentNode).toggleClass("enroute"); }); }); CSS: .placed{ b ...

Utilizing React.js to Sort Through JSON Data

I'm currently working with the following state: constructor(props){ super(props); this.state = { open: false, customers:[], customer:{}, products:[], product:{}, ...

Troubleshooting: Resolving JSX props issue in Vue template

Ever since integrating the FullCalendar library into my Vue project, I've been encountering an error every time I try to use my custom component in a Vue template. My setup includes Vue 3, Vite, VSCode, eslint, and prettier. This issue seems to be m ...