Is it possible to include a button in a search bar while maintaining the keypress functionality in Vue?

My search function is operational, but it currently requires the user to press the enter key to display results. I am interested in adding a button option for users as well. Users should be able to find results by either pressing enter or clicking the button. Can someone assist me with this?

<div class="search-box">
    <input 
      type="text" 
      class="search-bar" 
      placeholder="Search..."
      v-model="query"
      @keypress="fetchWeather"
    />
   <button>Click Me!</button>
  </div>

    methods: {
        fetchWeather (e) {
          if (e.key == "Enter") {
            fetch(`${this.url_base}weather?q=${this.query}&units=metric&APPID=${this.api_key}`)
              .then(res => {
                return res.json();
              }).then(this.setResults);
          }
        },
        setResults (results) {
          this.weather = results;
        }

Answer №1

To trigger the fetchWeather function for input, you can utilize

@keyup.enter="fetchWeather"
, and for a button use @click="fetchWeather".

Answer №2

To ensure proper functionality, simply include @click="retrieveForecast" within the button element, as shown below:

<button @click="fetchWeather">Press here to view details"

Answer №3

Give this a shot :

const app = new Vue({
  el: '#app',
  data: {
    query: null,
    queryData: ['search1', 'search2', 'search3', 'search4'],
    searchedData: []
  },
  mounted() {
    this.searchedData = [...this.queryData]
  },
  methods: {
    fetchWeather() {
      if (!this.query) return;
      this.searchedData = this.queryData.filter(item => item.includes(this.query))
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input 
         type="text" 
         class="search-bar" 
         placeholder="Search..."
         v-model="query"
         @keyup.enter="fetchWeather"
         />
  <button @click="fetchWeather">Click Me!</button>
  
  <ul>
    <li v-for="(item, index) in searchedData" :key="index"> {{ item }} </li>
  </ul>
</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

Uploading files with Multer and handling the JSON object

Is there a way to send both a file and a JSON object containing data using multer? I came across this thread, but it only explains how to attach one field at a time. Here's what I currently have on the client side: request .post(uploadPOSTUrl) . ...

Creating a Dynamic Canvas Rendered to Fit Image Dimensions

I'm struggling with a piece of code that creates an SVG and then displays it on a canvas. Here is the Jsbin Link for reference: https://jsbin.com/lehajubihu/1/edit?html,output <!DOCTYPE html> <html> <head> <meta charset=&qu ...

What is the best way to create text boxes that can expand and collapse within a UIWebView?

I am looking to present text in a UIWebView with expandable or collapsible boxes that contain titles. The user should be able to tap the bar of a collapsed box to expand it. Is there a simple solution available that can be easily integrated into a local ...

What is the process of updating values in an object that is part of an array?

I am currently facing an issue where I am attempting to implement an edit function to replace text and dates. While I have managed to successfully update the text using the DOM, the edited values revert back to their original form upon page refresh. I susp ...

Multiple presentations on a single webpage

I'm encountering some difficulty trying to incorporate multiple slideshows onto a single page. Currently, I am able to successfully add two operational slideshows, but as soon as I attempt to introduce a third one, everything becomes unstable. Would ...

Tips for avoiding the 'Duplicate keys detected' error when using a v-for loop in Vue.js

In my most recent project, I utilized Nuxt.Js along with Vuetify.js as the UI framework. The language I used was TypeScript. As part of this project, I attempted to create the image below using arrays. https://i.sstatic.net/t1Xsc.jpg export const dumm ...

What is the best way to loop through an object while keeping track of its value types

I have a JSON file containing UI adjustments sourced from the API: interface UIAdjustmentsJSON { logoSize: number; themeColor: string; isFullScreen: boolean; } To simplify things, let's utilize a static object: const adjustments: UIAdjust ...

Tips for measuring the number of elements in a table using Angular

Need assistance with code for an Angular app that uses ngFor to populate a datatable. The goal is to count the number of columns with the name "apple" and display the total on a card named 'apples'. I attempted to create a function like this: ...

Improprove Your Code Efficiency Using ng-repeat and ng-if

Hello everyone, Here is the structure of my table : https://i.sstatic.net/rTbiC.png The code for the table is as follows: <tr ng-repeat="item in captions | filter:search:strict"> <td>{{item.CodeId}}</td> <td>{{item.EnumC ...

Maintain the button's color when clicked UNTIL it is clicked again

I am facing a challenge where I need to dynamically select multiple buttons that change color upon click. Once a button is clicked, it should change color and if clicked again, revert back to its original color. Unfortunately, I cannot rely on HTML attribu ...

How can I change a string into hexadecimal code (0x000000) for Three 3d Objects using JavaScript?

I'm attempting to create a multitude of objects simultaneously while aiming for the color to gradually fade. Nonetheless, despite using .toString(16) to form a string, there seems to be an issue with this line of code: new THREE.MeshBasicMaterial({ co ...

How to effectively leverage useMediaQuery in material ui?

Upon completing the web application, I have made the decision to ensure it is mobile-friendly. Utilizing the material UI framework with react, I delved into the documentation but found myself uncertain about how to effectively implement it. Let me provide ...

Adding dynamic rows in JavaScript while ensuring proper spacing

I am currently working on dynamically adding a span element with an onclick event. $.ajax({ url:path, type: "POST", contentType: false, // To avoid setting any content header processData: fa ...

What is the best way to retrieve and utilize this JSON information with D3?

Understanding how to load JSON in D3 is crucial for working with data visualization. The process involves using the following code snippet without encountering any errors: d3.json("sample_data/unique_items.json", function(json) { // do something }); Af ...

How can Vue.js update the displayed information when the selection option changes?

Ensuring the total weight of the products remains accurate when changing the unit of measurement is essential. Currently, although the data in the array is being updated, these changes are only reflected on the screen after clicking on other input fields. ...

Remove the class upon clicking

I recently created a toggle-menu for my website that includes some cool effects on the hamburger menu icon. The issue I am facing is that I added a JavaScript function to add a "close" class when clicking on the menu icon, transforming it into an "X". Whil ...

Is there a way to grab code from a different HTML page using JavaScript and jQuery when the user clicks on something?

After testing various codes for the intended purpose mentioned in the title, I have observed a peculiar behavior. The code from settings.html appears briefly and then disappears rapidly. Javascript: function load() { $("#paste").load("settings.html") ...

Troubleshooting MongoDB and Node.js: Issue with updating variables when inserting documents in a loop

As a newcomer to MongoDB, I'm facing a puzzling issue that has left me confused. In my dataset, I have an array of Employee objects structured like this: { "Name" : "Jack Jackson", "Title" : "Senior Derp Engineer", "Specialties" : [ "Kicki ...

Validating numbers in both Javascript and Rails

Update: Upon further examination, it appears that when the numbers are printed out, they are identical and only display two decimal places. Additionally, in my database, these values are stored as decimal type with precision 8 and scale 2. Within my Rail ...

Trouble arises when attempting to transfer cookies between server in Fastify and application in Svelte Kit

In the process of developing a web application, I am utilizing Fastify for the backend server and Svelte Kit for the frontend. My current challenge lies in sending cookies from the server to the client effectively. Despite configuring Fastify with the @fas ...