Concentrate on the initial input that has errors. There seems to be an issue with this.$refs.array[

I am working on focusing the first input that has an error, using vuelidate.

The issue lies with this.$refs.array[index].$el.focus()

An error in the console is shown as: Uncaught (in promise) TypeError: Cannot read property '0' of undefined."

However, if I use the ref name of the input instead of array, everything works fine!

In my mixin file, I have the following:

export default {
    async beforeRouteLeave(to, from, next) {
        if (this.isEditSchoolPage || this.isEditMode) {
            if (await this.showSavingDialog()) {

                if (this.$v && this.$v.$invalid) {
                    this.$v.$touch();
                    this.focusFirstError();
                    return;
                }

                await this.submit(true);
            }

            removeEventListener('beforeunload', this.leaveDialog);
        }
        next();
    },

    methods: {
        focusFirstError() {
            var invalidFields = Object.keys(this.$v.$params)
                .filter(fieldName => this.$v[fieldName].$invalid);

            if (invalidFields) {
                this.$refs.invalidFields[0].$el.focus();
                return;
            }
        },
    }
}

I have added ref="" in the component input as shown below:

<v-form-group :validator="$v.taxRate" label="Sales Tax Rate (%)" label-required>
    <form-input-formatted type="percent" v-model="taxRate" ref="taxRate"/>
</v-form-group>

By replacing

this.$refs.invalidFields[0].$el.focus();

With

this.$refs.taxRate.$el.focus();

The functionality behaves as expected.

Attached are some images from the console: ibb.co/s36vWBQ

ibb.co/0Jqm9jD

ibb.co/rwfNJ0w

Answer №1

Here is the solution:

this.$refs[invalidFields[0]].$el.focus();

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

Is it possible to adjust the height of a div based on different conditions

I'm currently working on a React project where I need to conditionally display a div above an existing one that covers the screen with an image. My goal is to have the existing div shrink in height, reducing the size of the image when the second div i ...

Trouble with Webpack compiling SCSS files

I'm struggling with setting up webpack to bundle my js react components, js modules, and compile my .SCSS files to css. Despite multiple attempts, I keep encountering errors. Below is an excerpt from my webpack.config.js: const webpack = require(&a ...

Stop the ongoing ajax request, initiate a new one, and then resume the initial ajax call

There's some doubt in my mind about whether this can be done. During a button click event, I am making two ajax calls. The first call uses jQuery ajax post to add data to the database, and the second call does the same with a different set of data. ...

What distinguishes directly assigning a processed value to a variable from first assigning without processing and then processing using the && operator?

Recently, I came across a function that takes a string parameter and then carries out some operations on it. Here is an example of how it was implemented: const val = this.searchParam && this.searchParam.trim().toLowerCase(); This made me wonder why the p ...

CSS Toggle failing to show updated styles

Initially, I successfully changed the font and color of text on Google using a simple code. However, when I attempted to incorporate it into a toggle on / off switch, the changes did not take effect. To address this issue, I sought assistance from ChatGPT ...

Maintaining the current image while awaiting the completion of the new image update

I have successfully implemented a script using setInterval along with the jQuery load function to periodically update an image tag. var refresh_days = setInterval(function() { $('#box_name').load("dynamic.php");}, 1000 ); While this setup wo ...

It seems that an issue has occurred indicating that something is not defined in the current context

Hello everyone, I'm struggling with a problem that I just can't seem to figure out. I've tried multiple solutions but this error keeps popping up and now I'm completely lost. Can someone please help me resolve this issue? The code in q ...

Struggling with Data Rearrangement using Map Reduce技

I'm struggling with pivoting my dataset using map reduce. Despite referencing the MongoDB cookbook for guidance, I'm encountering some strange errors. I aim to restructure the provided collection so that each user has a comprehensive list of all ...

When you click away from the div in AngularJS, it will automatically disappear

Whenever we click outside the div or in a window, the xyz should be hidden. const app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.showDropdown = false; $scope.helloClick = funct ...

Tips for utilizing 2 Vue JS master files in your Laravel Project

Is there a way to incorporate Vue JS into both the main admin panel and frontend of a Laravel project? The main challenge seems to be organizing the master file for both the admin panel and frontend. ...

Inserting a JavaScript script reference into the Script Manager during a partial postback with Microsoft AJAX

I've been attempting to insert a script reference into the script manager during a Microsoft AJAX Partial Postback, specifically when a user clicks on a link in an Update Panel. ScriptManager.RegisterClientScriptInclude(Page, Page.GetType(), "UniqueN ...

Create a captivating sliding effect on Windows 8 using a combination of CSS and JavaScript

I believe that using css3 alone can achieve this effect, but I'm struggling with understanding properties like 'ease' in css3. This is the progress I have made so far: http://jsfiddle.net/kwgy9/1/ The word 'nike' should slide to ...

Exploring Opencascade.js: Uncovering the Real Text within a TCollection_ExtendedString

I am currently attempting to retrieve the name of an assembly part that I have extracted from a .step file. My method is inspired by a blog post found at , however, I am implementing it using javascript. I have managed to extract the TDataStd_Name attribut ...

Using Vue JS to assign a computed value within a component

Is there a way to update the computed property in mycomponentone when the "Click me child" button is clicked? I am currently experiencing issues with this functionality... Interestingly, when I click on the "Click me parent" button, the props are successf ...

Accessing form data within Mongoose schema hooks via JavaScript

I have a form where I've split the content into two separate MongoDB schemas. I want to access variables that are within node.js/express.js directly in mongoose schema hooks, whether through pre or post hooks of the schema. Here are my files: expres ...

Modifying CSS classes using conditional statements and loops

var first_left = ['Photo', 'Info', 'Question 1', 'Question 2', 'Question 3', 'Question 4', 'Question 5']; var names = ['Abuela', 'Abuelo', 'Oma']; functio ...

Sending an object from Rails to Javascript

My MapsController is def show @outlet=OUtlet.all render 'maps/map' end In the view page map.html.erb, I iterate through each outlet to display their latitude and longitude: <% @outlet.each do |product| %> <%= product.latitu ...

Internet Explorer's support for the `<summary>` tag in HTML

Is there a method to enable the summary tag in Internet Explorer 11, such as using an external library? <details> <summary>Here is the summary.</summary> <p>Lorem ipsum dolor sit amet</p> </details> App ...

What is the total amount within a specified date range when retrieved as JSON?

Consider the following JSON structure: { "timesheets": [ { "user": { "username": "erik", "first_name": "Erik", }, &q ...

Application freezes when asynchronous lookup returns no results

While using mongoose with async, I have encountered an issue where my application hangs and eventually times out when performing a lookup that returns no results. Below is an example of a controller code snippet that performs a simple lookup by id using m ...