How can I check if a value inputted into a form is empty in Vue version 2?

I have attempted various methods using alert() and simple if-else statements, as well as referencing the guide available at this link.

However, none of these approaches seem to be effective. Can anyone point out what I might be doing incorrectly?

Here is a snippet from my index.html:

<div id="app">
    <div class = "addTask">
        <h1>A List of Tasks</h1>
        <p v-show="activeItems.length === 0">You are done with all your tasks! Celebrate!</p>
        <form @submit.prevent="addItem">
            <input type="text" v-model="title">
            <button type="submit">+</button>
        </form>
    </div>

This is a snapshot from scripts.js:

var app = new Vue({
    el: '#app',
    data () {
      return {
        // errors: [],
        items: [{
          userId: 0,
          id: 0,
          title: "",
          completed: false,
          }],
          title: '',
          show: 'all',
     }
    },
    mounted () {
      axios
        .get("https://jsonplaceholder.typicode.com/todos")
        .then(response => this.items = response.data)
    },
    computed: {
      activeItems() {
        this.saveItems;
        return this.items.filter(item => {
          return !item.completed;
        });
      },
      filteredItems() {
        if (this.show === 'active')
          return this.items.filter(item => {
            return !item.completed;
          });
        if (this.show === 'completed')
          return this.items.filter(item => {
            return item.completed;
          });
          return this.items.reverse();
      }, 
    },
    methods: {
      addItem() {

        if(this.items != 0) {
          this.items.push({
            title: this.title,
            completed: false
          })
          this.title = "";
        }
        else {
          alert("Please enter a task.")
        }

Answer №1

In your code, it is recommended to define a property named title within the data function and validate whether it is empty or not in the addItem method.

var app = new Vue({
  el: '#app',
  data () {
    return {
      // errors: [],
      title: '', // remember to include this property in the data function
      items: [{
        userId: 0,
        id: 0,
        title: "",
        completed: false,
        }],
        title: '',
        show: 'all',
    }
  },
  // Utilizing axios for asynchronous API calls
  mounted () {
    axios
      .get("https://jsonplaceholder.typicode.com/todos")
      .then(response => this.items = response.data)
  },
  computed: {
    activeItems() {
      this.saveItems;
      return this.items.filter(item => {
        return !item.completed;
      });
    },
    filteredItems() {
      if (this.show === 'active')
        return this.items.filter(item => {
          return !item.completed;
        });
      if (this.show === 'completed')
        return this.items.filter(item => {
          return item.completed;
        });
      return this.items.reverse(); // Move newly added tasks to the top
    },
    
  },
  methods: {
    addItem() {

      if(this.title !== '') { // Ensure `title` is not empty
        this.items.push({
          title: this.title,
          completed: false
        })
        this.title = "";
      }
      else {
        alert("Please enter a task.")
      }

A demonstration has been set up on Stackblitz. You can view the example directly by clicking here

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

Tips for accessing and modifying parent state resolve data within the onEnter function of a child state in a UI router

Within my ui-router state configuration, I have the following setup: Parent state $stateProvider .state('profile',{ url: '/profile', views: { 'contentFullRow': { ...

The scrolling navigation bar appears behind the slider, causing the parallax effect on the slider to not work properly

While I was scrolling down, my menubar went behind the cycle slider. I tried using z-index 1, but it's not working. Can anyone provide a solution? I'm not sure what I did wrong. </div> <img src="http://malsup.github.io/imag ...

Where might I locate the source files for a compass in a Windows operating system?

Is there a way to access certain compass mixins without actually including the entire compass library in my project? I'd prefer not to have to import compass directly, like in these examples: @import "compass"; @import "compass/reset"; @import "co ...

Converting Database Information to JSON Format for Mobile Authentication Form

Currently, I am working on a Mobile App project using Phonegap that requires users to log in before retrieving JSON data. This PHP page is responsible for connecting to the mobile site and fetching the necessary information. <?php $con = mysqli_connec ...

Morgan middleware in Express.js specifically targeting unsuccessful requests for logging purposes

Currently, I am facing an issue with my middleware setup in Express.js while using Morgan. The problem arises because Morgan is only logging requests that return error code 302 (redirected), which happens when my middleware encounters an error and redirect ...

What a great method to execute a button click within the same button click using jQuery!

Here's an example of code that attempts to make an ajax call when a user clicks a button. If the ajax call fails, the button should be reclicked. I've tried this code below, but it doesn't seem to work. $("#click_me").click(function(){ ...

Snapping a photo from the webcam for your profile picture

Is there a way to capture images using a webcam and upload them to a server in a PHP & Mysql application? I've been searching on Google but only find outdated code that is not supported in all browsers. Here are some links you can check out for more ...

Why is it necessary for me to constantly run npm run production in order to view any updates?

Currently, I am integrating Vue within Laravel. After making changes in the Vue code, I have noticed that these changes do not appear until I execute the following command: npm run production Is there a way to avoid having to run this command every time ...

The environmental variable remains undefined even after it has been established

I've been experimenting with setting my environment variable in the package.json file so that I can access it in my server.js file. Despite trying NODE_ENV=development, set NODE_ENV=development, cross-env NODE_ENV=development, and export NODE_ENV=deve ...

Integrate predictive text suggestions in JavaServer Pages for efficient form filling

After some research, I have managed to solve the issue I was facing. On my jsp page, I have three text boxes. When I enter data into the first text box, it triggers a call to get.jsp to fetch data from the database and populate the second text box. However ...

Having issues with dynamic router links on vue.js -- any suggestions?

Why is my page not loading properly when clicked on a router-link? When I click on each link, it displays correctly in the address bar but the page does not load or route. However, if I refresh the page, it then shows the correct content. [routes] ` imp ...

Searching for values using keys in Angular

Currently, I am working on a project using Angular where I need to store information based on specific identifiers. To display this information in the Angular application, I am pulling data for different identifiers and showing it on the screen. At the mo ...

Guide on transferring data from a JSON file to a JavaScript array

Currently, I am manually declaring the countries list for my typeahead search. To streamline this process, I want to retrieve the data from an external JSON file named countries.json. Here is a snippet of what the JSON file contains: [ { "id": ...

"From transitioning from a regular class to a functional component in React Native, navigating through the

I am a beginner in react native and I am struggling to convert class components into functional components. I have tried various ways to pass refs in the functional component and used hooks to manage state, but unfortunately, I haven't been successful ...

Problem with email verification process

Hey there, I'm currently working on validating an email address using regular expressions. Here is the code snippet I'm using: <input type="text" name="email" id="email"/> var email = $("input#email"), re = /^[A-Za-z ...

Retrieving the JSON value from a data attribute and then locating the corresponding JSON key in a designated element within the DOM

I have an HTML element that contains a data attribute: <a href="#" data-trigger="{ "rem": "albatros", "ap":1 }'">Remove</a> <div data-container> <p>lorem ipsum<p> <p data-rem></p> </div> 1. So ...

Promise refused due to non-error caution

Error: h1.js:25 Warning: a promise encountered an issue with a non-error: [object String] I am unsure of the root cause of this error and would greatly appreciate any assistance in understanding it. I am currently learning about Promises and AJAX, so any ...

What is the best way to obtain a user's ID on the server side?

I'm currently working on a node.js application using express and I am in need of retrieving the user ID. I would like to have something similar to "req.userID" so that I can use it in the following way: var counter=0; var user = new Array(); router.g ...

Unable to access variables beyond the function scope results in an undefined value

I'm currently working with an npm package that shortens URLs but I'm struggling because there isn't much documentation available. The package takes the "this.src" URL and shortens it, but when I try to use the "url" element in HTML, it retur ...

Ensure that images in a browser maintain their proportions without distortion on all device screens and orientations by setting their height and width to match the

I'm working on a slideshow component in React and I want the images to dynamically adjust to fit any device screen size and orientation. The goal is for the image to resize proportionally until it reaches either the top and bottom edges or left and ri ...