Get all inputs with the same text using Vue 3 composition API and a single ref, or access multiple inputs with the

One of the challenges I'm facing is managing multiple instances of a component called InputWithValidation within a form. I need to check if all instances are valid at once.

For a single instance of InputWithValidation, I can easily verify its validity like this:

<script setup>
   import { ref } from 'vue'
   const inputEmail = ref(null);

   function submit(){
      if(inputEmail.isValid()){
         //call API
      }
   }
</script>
<template>
   <form>
      <InputWithValidation ref="inputEmail" type="email" validationType="EMAIL"/>
      <button @click="submit">Submit</button>
   </form>

</template>

However, dealing with multiple instances poses a challenge:

<template>
   <form>
      <InputWithValidation ref="inputEmail" type="email" validationType="EMAIL"/>
      <InputWithValidation ref="inputFirstName" type="text" validationType="TEXT"/>
      <InputWithValidation ref="inputEmail" type="text" validationType="TEXT"/>
      <!-- ... -->
      <button @click="submit">Submit</button>
   </form>
</template>

I don't want to individually declare each instance like this:

<script setup>
   import { ref } from 'vue'

   const inputEmail = ref(null);
   const inputFirstName = ref(null);
   const inputEmail = ref(null);
   //....
</script>

To tackle this issue, I tried using an array in my ref to capture all instances and validate them together:

<script setup>
   import { ref } from 'vue'
   const inputs = ref([]);

   function submit(){
      if(inputs.find(input => !input.isValid()) == null){
         //call API
      }
   }
</script>
<template>
   <form>
      <InputWithValidation ref="inputs" type="email" validationType="EMAIL"/>
      <InputWithValidation ref="inputs" type="text" validationType="TEXT"/>
      <InputWithValidation ref="inputs" type="text" validationType="TEXT"/>
      <button @click="submit">Submit</button>
   </form>
</template>

Unfortunately, this approach did not work as expected.

Does anyone know of a way to retrieve all references (refs) at once?

Answer №1

One way to manage all your "input" elements in a JavaScript data structure with Vue is by utilizing the concept of "Function Refs".

In your template, you can assign input elements like this:

<InputWithValidation ref="myAddRefFunction" ... />
<InputWithValidation ref="myAddRefFunction" ... />
etc

Then, in the script setup section, define the following functions:

const inputRefs = ref(new Set())

function myAddRefFunction(el) {
  inputRefs.value.add(el)
}

async function ValidateAll() {
  const validationResults = []
  for (const inputComponent of inputRefs.value) {
     validationResults.push(await inputComponent.validate())
  }
  return validationResults
}
  

Implementing something similar should help you achieve your goal.

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

Adding a thousand separator feature to a React Mui TextField

I'm having trouble with my TextField in MUI. I have successfully separated the digits, but now I want to add a thousand separator to the value. Here is my code snippet: <TextField size='small' label ...

Steps for instructing Google Maps to identify the location of a provided Google Maps URL

Is it possible to extract longitude and latitude data from a shared URL and place them into a marker? For example, users might copy and paste the 'Share' URL from Google Maps. For instance: or Direct Location: https://www.google.co.nz/maps/plac ...

Modifying an image's src using JavaScript is not possible

I'm attempting to modify the source of an image using a JavaScript function, but it doesn't seem to be working. The function is being executed within a mounted() method in Framework7. Here is my current setup: HTML: <div> <span> &l ...

Adjusting the size of images in real time

Currently, I am in the process of creating a Fluid grid style website and I am looking to decrease the size of all images by 75% when the screen is below 1280px, 50% at 800px, and so forth. Is there a way to achieve this using the IMG tag? My attempt so ...

Utilize jQuery to dynamically add or remove elements by referencing specific HTML elements

My goal is to dynamically add an element to a dropdown menu and then remove it after selection. I initially attempted to define the htmlElement reference in this way: (Unfortunately, this approach did not work as expected) var selectAnOption = "<option ...

ASP.NET "Data" Error: Trouble Parsing JSON Data on the Front-End

I am currently facing an issue with the configurations on my asmx page. The code is set up like this: using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.Script.Serialization; using Syst ...

How can I utilize JavaScript to generate a dynamic value in a URL and then submit it through a form?

One of my clients has requested the ability to send out unique URLs to their customers in order to track which links are being utilized. Despite my suggestion to use Google Analytics for this purpose, they have specifically asked to avoid it. Their reques ...

When using the jQuery ajax function to validate a form, it is important to note that the $_POST variables

I have an HTML form along with a jQuery function for form validation. After submitting the form values to my PHP files, I notice that the $_POST variable is not being set. What could be causing this issue? <form id="signup" class="dialog-form" action= ...

The Enum object in TypeScript has not been declared or defined

For my TypeScript application, I am utilizing WebPack to transpile and bundle the code. The final result is intended to be used in a pure JavaScript website. One of the components in my application is an enum defined as follows: export const enum ShapeTyp ...

The solution for fixing contenteditable is as follows:

I am currently working on a script to clean up pasted text within a contenteditable div. While the script is functioning well for most part, I have noticed that in Firefox, line breaks get removed when the text is copied within or between the divs. Does ...

Issue encountered: The function car.reviews.find() is not recognized

Encountering an issue with the find() method in my MERN stack application. I am looking to implement a reviews route where users can add comments about cars within the app. In the frontend, fields and buttons have been added; meanwhile, a post request has ...

Using Express to Deliver Static Content to Subdirectories

I am currently using Express to serve a React application that was bootstrapped with Create React App. The project has the following directory structure: |--client/ | |--build/ | | |--static/ | | | |--main.css | | | |--main.js | ...

Does Three.js come with a default function for generating heightmaps?

Currently, I am engrossed in developing a JavaScript game using Three.js. My interest lies in enhancing the realism of the walls by incorporating a height map (refer to the provided image). View this snapshot of the game design featuring a 2D wall. All th ...

What is the best way to display text based on the current URL?

Using vue-router, I am attempting to maintain a title that specifies the section. For instance: In the main navigation, I want to display the text of the current section (not the active class, just plain text with the section). Here is the pattern of URL ...

Troubleshooting issues with the 'apple-app-site-association' file in a Vue.js project utilizing the nuxt.js framework

Currently working on a project using Vue.js and nuxt.js, I am trying to add the "apple-app-site-association" file to my website. The steps I took so far are as follows: I placed the "apple-app-site-association" file in the public folder under "static" Th ...

Using MIPS Assembly Language: Displaying Register Content on Screen

I'm working on replicating a simple form of debugging in MIPS similar to javascript. I am wondering how I can achieve the equivalent of this ($t0 represents a javascript variable here): console.log($t0); In simpler terms, I am looking for the metho ...

Certain images are not being retrieved by Express on Linux, although they are functioning properly on Windows

When using a template to display HTML code, everything works smoothly on Windows. However, when transferring the code to a Linux machine, an issue arises - "Cannot GET /SmallVacImages/1.jpg". It seems that the index.html file can load images from the publi ...

Once appearing, the element quickly vanishes after the fadeIn() function is

In the source code, there is a section that looks like this: <div class="dash page" id="home"> <?php include ('pages/home.php'); ?> </div> <div class="dash page" id="screenshots"> <?php include ('pages/scr ...

Creating a Class in REACT

Hello fellow coding enthusiasts, I am facing a minor issue. I am relatively new to REACT and Typescript, which is why I need some assistance with the following code implementation. I require the code to be transformed into a class for reusability purposes ...

"Learn how to deactivate the submit button while the form is being processed and reactivate it once the process is

I have been searching for solutions to this issue, but none seem to address my specific concern. Here is the HTML in question: <form action=".."> <input type="submit" value="download" /> </form> After submitting the form, it takes a ...