Is an if-else statement needed to highlight empty fields on form submission in Vue.js?

When attempting to use the if-else function, I noticed that it behaves as expected when there is an empty field (it will focus on the input first) or if there is a value in the input, then the form can be submitted. However, when I tried to enter some text into the input and then remove it, the if-else function no longer works the same way. How should I proceed?

<!doctype html>
<html>

<head>


    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc8a899988959a85bcced284">[email protected]</a>/dist/vuetify.min.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="45232a2b3105766b3d">[email protected]</a>/css/materialdesignicons.min.css" />
    <link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88eae7e7fcfbfcfae9f8a5fefdedc8baa6b8a6b8a5faeba6b9b9">[email protected]</a>/dist/bootstrap-vue.css" rel="stylesheet" />
    <link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f5d50504b4c4b4d5e4f7f0b110e110c">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>

<body>
    <div id="app">
        <v-app>
            <v-content>
                <v-container>
                    <b-form @submit="onSubmit">
                        <b-row>
                            <b-col>
                                <v-combobox v-model="answer.type_a" :items="type_a" label="a" multiple ref="type_a">
                                </v-combobox>
                            </b-col>
                            <b-col>
                                <v-combobox v-model="answer.type_b" :items="type_b" label="b" multiple ref="type_b">
                                </v-combobox>
                            </b-col>
                        </b-row>

                        <v-btn type="submit" color="primary">Submit</v-btn>

                    </b-form>

                </v-container>
            </v-content>
        </v-app>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b0d0e1e3b495503">[email protected]</a>/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="64121101100d021d24564a1c">[email protected]</a>/dist/vuetify.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd9f9292898e898f9c8dd08b8898bdcfd3cdd3cdd08f9ed3cccc">[email protected]</a>/dist/bootstrap-vue.min.js"></script>
</body>
<script>
    new Vue({
      el: '#app',
      vuetify: new Vuetify(),
      data: () => ({
        type_a: ["a", "b"],
        type_b: ["c","d"],
      
        
        answer: {
          type_a: "",
          type_b: "",
        },

      }),
       methods: {
        focusInput: function(inputRef) {
          this.$refs[inputRef].focus();
        },
         
       onSubmit(evt) {
      evt.preventDefault();

      if (this.answer.type_a !== "" && this.answer.type_b !== "") {
        axios.post("/", this.answer)
          .then(() => {
            console.log("SUCCESS!!");
          })
          .catch(() => {
            alert("FAILURE!!");
          })
      } else {
        if (!this.answer.type_a) {
          this.focusInput("type_a");
          return ;
        }
        if (!this.answer.type_b) {
          this.focusInput("type_b");
          return ;
        }
        // return true;
      }
    },

         
         

      }

    })

</script>

</html>

In this basic HTML snippet, the desired functionality is that upon submitting the form, if any of the fields are empty, the form should focus on that specific input field. If there is a value in all inputs, the form submission should be allowed.

<form>
    <input type="text" name="username" required>
    <input type="text" name="password" required>
    <input type="submit">
</form>

Answer №1

How v-if is implemented in Vue.js

I have enhanced your code to demonstrate the utilization of v-if within the template. By leveraging Vue's feature of rendering HTML content based on JavaScript variables' conditions, I rearranged the code around the SUBMIT button.

The presence of v-if within a div tag ensures that the div is only displayed if the condition specified by v-if evaluates to true. This strategy enables you to reveal each question sequentially as users progress, with the option to automatically set focus using the autofocus attribute.

This approach surpasses displaying an extensive list of unanswered questions, which often leads users to realize their incomplete status after clicking Submit. It's more effective to direct their attention consistently towards completing the immediate task rather than surprising them later.

<!DOCTYPE html>
<html>
  <head>
    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900"
    />
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7a1a2b2a3beb1ae97e5f9af">[email protected]</a>/dist/vuetify.min.css"
    />
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a0c05041e2a594412">[email protected]</a>/css/materialdesignicons.min.css"
    />
    <link
      href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f89a97978c8b8c8a9988d58e8d9db8cad6c8d6c8d58a9bd6c9c9">[email protected]</a>/dist/bootstrap-vue.css"
      rel="stylesheet"
    />
    <link
      href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9aba6a6bdbabdbba8b989fde7f8e7fa">[email protected]</a>/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
  </head>

...
...
...


        },
      },
    });
  </script>
</html>

Answer №2

A more efficient way to handle this would be using Vue's reactivity feature.

One suggestion is to display the "Submit" button only after all the necessary data has been entered.

<v-combobox v-model="answer.type_a" :items="type_a" label="a" multiple ref="type_a">
</v-combobox>

<v-combobox v-model="answer.type_b" :items="type_b" label="b" multiple ref="type_b">
</v-combobox>

<div v-if="answer.type_a && answer.type_b">
    <v-btn type="submit" color="primary">Submit</v-btn>
</div>
<div v-else>
    Both entries are required
</div>

The inclusion of the "if-then" logic in the HTML makes it easier to understand the code structure. By ensuring that valid answers trigger the visibility of the button, users will be prompted with a message if both entries are not completed.

Will this information be sufficient for you to begin?

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 are the appropriate situations to utilize Q.defer versus using Promise.resolve/reject?

I've been working with nodejs and I'm curious about when to use Q defer over Promise.resolve/reject? There are numerous examples of both methods, such as: // using Q defer function oneWay(myVal) { var deferred = Q.defer(); if (myVal < 0) ...

Resetting the positions of images can be done by following these

I'm currently in the process of developing a game and need assistance with implementing a game end function. Can you provide guidance on how to reset all images back to their original positions? ...

Accessing Public Photos from Facebook Users

Is it possible to create a web app that can retrieve all public photos from any user's Facebook account using their profile URL? For instance, some Facebook profiles allow non-logged in users to view profile pictures and cover photos. I am developing ...

Revamping the website to become a Progressive Web App

I am in the process of transforming my website into a Progressive Web App (PWA) and have made some updates to my code to facilitate this: index.html <script> if('serviceWorker' in navigator) { navigator.serviceWorker.registe ...

Creating dynamic height based on width using JavaScript

I'm trying to make a rectangle responsive based on the width of the window. This is my current logic: aspectRatio = 16 / 9 win = { width: window.innerWidth, height: window.innerHeight, } get browser() { const width = this.win.width - 250 ...

Creating dynamic object rotation based on a new pivot point using Three.js

In Three.JS, I've successfully created a spiral with downward movement. However, I am struggling to implement the knocking motion. https://i.sstatic.net/VrykN.gif var planeGeometry = new THREE.PlaneGeometry(10,10); var planeMaterial = new THREE.Mesh ...

Guide to utilizing Vue.js method functions to add a thousand separator in the passed props

As a beginner in Vue.js, I am trying to add a thousand separator to the price passed as a prop using a method called 'thousandSeparator'. However, I am having trouble figuring out how to implement this. I have managed to parse the props price, b ...

Drop-down menu for every individual cell within the tabular data

I'm working with a large HTML table that looks like this: <table> <tr> <td>value1</td> <td>value2</td> </tr> <tr> <td>value3</td> <td>value4 ...

PL/SQL Process in Oracle APEX fails to respond when triggered via AJAX before the page unloads

In my Oracle APEX 4.2 environment, I created a PLSQL process set to execute "On Demand - When this process is called by AJAX." The purpose of this process is to update two member attributes in a collection that I established when the page loaded. Here is t ...

Having trouble installing vue cli, attempted both yarn and npm but neither are functioning properly?

I've been attempting to set up Vue CLI but encountering an error: NPM warns that [email protected] has been deprecated. More info at https://github.com/request/request/issues/3142 NPM also warns about [email protected]. Deprecated link: ht ...

jQuery encountering TypeError while attempting to retrieve JSON data

Attempting to retrieve JSON data from the following URL using the provided code snippet: $.ajax({ type: "GET", url: "https://covid.ourworldindata.org/data/owid-covid-data.json/", success: function (data) { $("h5").e ...

Incorporating React Native elements into a native Android interface (UI element)

I am facing an issue in my react-native application where I have a native Android view (created in java) rendering correctly. However, when I attempt to include one of my react-native javascript components within it, I encounter this error: java.lang.Cla ...

Preserve Vue router nested components even after navigating to different pages

Need help with this problem: https://jsfiddle.net/guanzo/myn5o94e/1/ The app defaults to /bar. When you click on "Go to bar child", it goes to /bar/barchild and shows the BarChild component. Clicking on "Go to Foo" navigates to /foo. If you then click on ...

VueJS displays an error message stating: "Component '<IncomeList>' is not recognized - have you properly registered the component?"

As a junior student, I attempted to create a simple exercise using the income-tracker tutorial at https://www.youtube.com/watch?v=AjV7k7t78Ik, but encountered an error that I'm struggling to resolve. [Vue warn]: Unknown custom element: <IncomeList ...

Fetching information from server proves to be sluggish within AngularJS application

In the process of developing a web application, I am faced with the task of sending numerous $http requests to the server. My front-end is built using AngularJS while the back-end utilizes ExpressJS. The $http requests are currently being made as shown in ...

Steps to remove a script upon clicking a button?

On my website, I have integrated a plugin called manychat using a <script>. However, when I click on the Drawer Cart, the manychat symbol overlays over the checkout button, which is not visually appealing. Is it possible to unload this script when ...

Color schemes for items in the Windows store app

I'm having trouble changing the background color of an item in my split application. I've tried using CSS, but nothing seems to work. Here is the template for the item (default style): <div class="itemtemplate" data-win-control="WinJS.Bindin ...

How to dynamically disable options in a Vuetify v-select based on the type of object value

When utilizing the Vuetify v-select component and setting the prop multiple, we can select multiple values at once. In this scenario, I have a variety of recipes categorized under Breakfast or Dinner using the parameter type. The goal is to deactivate al ...

View real-time data in Vuejs 3 as it executes

I am currently working on a form that populates a table with data retrieved from a Laravel API. I am using Vue.js 3 and Composition API to build my entire application. When the button is clicked, I want the table to be filled with data from the form. The b ...

When the mouse leaves, the background image will revert back to its original setting

https://i.stack.imgur.com/Ojd0Q.pngI need assistance in reverting a div's background image back to its default state using the onmouseleave method. Below is the HTML and JS code I have been working on: <script type="text/javascript"> functi ...