Display an error message if the input field is empty, then conceal the message once the input field is filled

Can anyone assist with a Vue.js app issue I'm facing? Currently, when the search input is empty, an error message appears - which is okay. However, I want to hide this error message as soon as the user starts typing in the search field. The code for my component includes both template and script sections:

<template>
  <div class="jumbotron">
    <h1 class="display-4">{{title}}</h1>
    <p class="lead">{{intro}}</p>
    <hr class="my-4">
    <p v-if="errors.length">
      <b>Please correct the following error(s):</b>
    </p>
    <p v-for="(error, index ) in errors" :key="index">{{ error }}</p>
    <input
      class="form-control form-control-lg mb-3"
      type="search"
      placeholder="Search"
      aria-label="Search"
      v-model="search"
      required
    >

    <div class="loading" v-if="loading"></div>

    <table class="table table-sm table-light table-bordered" v-if="result.length">
      <thead class="thead-dark">
        <tr class="col-8">
          <th scope="col">Name</th>
          <th scope="col">Artist</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(result, index) in result" :key="index">
          <td>{{result.collectionName}}</td>
          <td>{{result.artistName}}</td>
        </tr>
      </tbody>
    </table>
    <button
      class="btn btn-success btn-lg btn-block mb-3"
      type="submit"
      v-on:click="getData"
      v-if="result.length < 1"
    >Get data</button>
  </div>
</template>

<script>
export default {
  name: "Hero",
  props: {
    navLink: String
  },
  data: function() {
    return {
      title: "Simple Search",
      intro: "This is a simple hero unit, a simple jumbotron-style.",
      subintro:
        "It uses utility classes for typography and spacing to space content out.",
      result: [],
      errors: [],
      search: "",
      loading: ""
    };
  },

  watch: {
    search: function(val) {
      if (!val) {
        this.result = [];
      }
    }
  },

  methods: {
    getData: function() {
      this.loading = true;
      fetch(`https://itunes.apple.com/search?term=${this.search}&entity=album`)
        .then(response => response.json())
        .then(data => {
          this.result = data.results;
          this.loading = false;
          console.log(data);
        });
      if (this.search) return true;
      this.errors = [];
      if (!this.search) this.errors.push("Enter search field.");
    }
  }
};
</script>

I would appreciate any suggestions on whether I should modify the v-if statement or make changes within the script tag to achieve this requirement.

Answer №1

Make sure to keep an eye on the search attribute, and if it is not filled out, update the errors array:

methods: {
  getData: function() {
    this.loading = true;
    fetch(`https://itunes.apple.com/search?term=${this.search}&entity=album`)
      .then(response => response.json())
      .then(data => {
        this.result = data.results;
        this.loading = false;
        console.log(data);
      });
  }
},
watch: {
  search: function(val) {
    if (!val) {
      this.result = [];
      this.errors = [];
      this.errors.push("Please enter something in the search field.");
    }
  }
}

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

Order objects in a JavaScript array

Recently, I came across a list of student data fetched from an API: const Studentdata = { "StudentName1": { "active": true, "gender": "male" }, "StudentName2": { "active": false, "gender": "male" }, "S ...

Loading local JSON data using Select2 with multiple keys can greatly enhance the functionality

Comparing the select2 examples, it is evident that the "loading remote data" example contains more information in the response json compared to the "loading array data" example. I am interested in knowing if it is feasible to load a local json file with a ...

How can an additional value be sent to the form validation method?

I have created a form group like this: import { checkPasswordStrength } from './validators'; @Component({ .... export class PasswordComponent { ... this.userFormPassword = this.fb.group({ 'password': ['', [ ...

Puppeteer cannot fully render SVG charts

When using this code in Try Puppeteer: const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.barchart.com/futures/quotes/ESM19/interactive-chart/fullscreen'); const linkHandlers = await pa ...

What is the process by which node.js synchronously delivers a response to a REST web service?

Sorry if this question seems obvious! I'm struggling to grasp how node.js handles requests from the browser. I've looked at tutorials online where express.js was used to create the server-side code with node.js. Routes were then set up using prom ...

Repetitive cycling through an array

My array consists of classes: const transferClasses = [ { id: "c5d91430-aaab-ed11-8daf-85953743f5cc", name: "Class1", isTransfer: false, children: [], }, { id: "775cb75d-aaab-ed11-8daf-85953743f5cc", ...

capturing webpage content with javascript for use in a screenshot

Is there a way to capture a screenshot of a webpage using JavaScript and utilize the canvas tag for this purpose? I attempted to use the html2canvas plugin in the past, but found it lacking in power. I would like to achieve this without relying on extern ...

Troubleshooting: Unable to locate .vue.d.ts file during declaration generation with Vue, webpack, and TypeScript

Currently, I am developing a library using Typescript and VueJS with webpack for handling the build process. One of the challenges I'm facing is related to the generation of TypeScript declaration files (.d.ts). In my source code, I have Typescript ...

What is the purpose of using an img tag to retrieve a URL that is not an image?

Upon investigating a slow page load, I came across something interesting in the HTML: <img src="/ajax?action=askedAboutCookies" style="display:none" width="0" height="0" alt="" /> When the page loads, it sends a request but never receives a respons ...

Show or hide the sibling element of the current element without using a specific identifier in jQuery

I am looking to make div.edit-button toggle its corresponding sibling div.additionalFieldForm. There are multiple instances of both on the page, so I want to target only the pair that are related within the same group. If a div.edit-button is clicked, the ...

Trouble with CSS loading in Vuetify causing delays

While working on my webapp using Nuxt.js + Vuetify, I encountered a delay in the CSS of certain elements after deploying it on Google App Engine. You can see an example of this delay in this GIF. Is there a way to prevent or fix this delay? ...

The process of flattening an array in Zustand: a comprehensive guide

In my array of brands, each brand object includes a brand name and products. Initially, I successfully added a new brand object to the brands list. However, when attempting to add another brand while keeping the previous brand data intact, it does not fu ...

Acquiring data within a jade template in order to generate static HTML pages

I am struggling to pass data to a jade template in order to generate static content. While I am not well-versed in node.js and express, I use jade as a template engine for creating static html. Many of the requests in the jade issue list pertain to includ ...

What is the best way to customize a component in a view?

<template> <div class="about"> <Header /> <h1>Welcome to the dashboard page</h1> </div> </template> <script> import Header from "../components/layout/Header.vue"; export default { name: "dashb ...

Holding off on completing a task until the outcomes of two parallel API requests are received

Upon page load, I have two asynchronous API calls that need to be completed before I can calculate the percentage change of their returned values. To ensure both APIs have been called successfully and the total variables are populated, I am currently using ...

What could be causing the `unstable_Profiler` to not function properly in production mode?

Encountering a problem with unstable_Profiler in my React-Native project where the onRender callback is being ignored, but only in production mode. No errors are being thrown and everything renders correctly. I followed the advice from this article: I tes ...

Mastering the Art of Sending Multiple Values via Ajax

I'm having trouble passing multiple values using ajax in my code snippet. Here is the code I am working with: $(".ajax-button").change(function(event){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': '{{ ...

Transferring JSON data using DWR (Direct Web Remoting)

Utilizing DWR for AJAX calls in my project involves the conversion of JavaScript objects to Java objects by analyzing the Java class. My goal is to send and receive a JSON-like structure through DWR. For example: JavaScript Object: { "name" : "TamilVe ...

Struggling to comprehend the filtering arguments in VueJS?

While going through the VueJS Filter(orderby) API documentation, I came across some confusion regarding the arguments. Below is a sample for reference: Arguments: {String | Function} targetStringOrFunction "in" (optional delimiter) {String} [...s ...

VS Code lacks autocomplete intellisense for Cypress

I am currently using Cypress version 12.17.1 on VS Code within the Windows 10 operating system. My goal is to write Cypress code in Visual Studio Code, but encountered an issue where the cypress commands that start with cy are not appearing as auto-comple ...