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

How to Stop Element Flickering While Hovering in Selenium IE Webdriver

My code is functioning perfectly in Firefox, but when I try it on Internet Explorer, there is flickering. Here is my code: WebElement mouseOver= driver.findElement(By.linkText("abc")); //I'm locating the element by link text. Selenium finds the ...

Hey there, I'm looking to use different CSS fonts on Windows and Mac for the same page on a web application. Can someone please guide me on how to accomplish this?

In order to tailor the font based on the operating system, the following criteria should be followed: For Windows: "Segoe UI" For Mac: "SF Pro" Attempts have been made using the code provided below, but it seems to load before the DOM and lacks persisten ...

Following the upgrade of Angular, the webpack module source-map-loader is encountering an error: "this.getOptions is not a function"

Currently in the process of constructing my angular project using webpack alongside source-map-loader to extract source maps, like this: module.exports = { // ... module: { rules: [ { test: /\.js$/, enforce: "pre&quo ...

Dynamic Text Labels in Treemap Visualizations with Echarts

Is it possible to adjust the text size dynamically based on the size of a box in a treemap label? I haven't been able to find a way to do this in the documentation without hardcoding it. Click here for more information label: { fontSize: 16 ...

Troubleshooting issue with Express.json() functionality in the latest release of version 4.17

I'm currently exploring the MEAN stack and I am focused on performing CRUD operations. However, when I send data in the request body from Angular to the server, I end up receiving an empty request body. I'm unsure of where I might be making a mis ...

Using radio buttons and a price slider, a unique jQuery filter for products can be

I have successfully implemented basic functionality to filter products based on price (slider) and radio boxes. However, the current filter system uses OR logic, but I need it to use AND instead. For instance, I want to find a product that is from Brand1, ...

Dealing with extended render times in React applications

Currently, I'm working with a limited set of 100 documents per page and utilizing a wrapper component for certain conditional actions. const onClickCheckbox = (order: OrderProps) => { const _ordersToExport = [...ordersToExport]; const ind ...

Adding parameters to a URL is a common practice

"Adding additional information to a URL that was previously included?" I apologize for the confusing title, but I can't find a better way to phrase it. Perhaps an example will make things clearer. Let's say I have URL 1: http://example.com/?v ...

Identical Identifiers in jQuery Tab Elements

Currently, I am utilizing the jQuery Tabs library within a small application. Within this page, there are 5 tabs that load content using Ajax. However, an issue arises when a tab is loaded and remains in the browser's memory along with its HTML elemen ...

Adding a hash to asset paths in NextJS static builds

After running next build && next export, I receive a directory named out, which is great. When examining the source code, such as in the index.html file, it requests assets from <link rel="preload" href="/_next/static/css/styles.aa216922.chunk. ...

What is the most effective way to identify mobile browsers using javascript/jquery?

As I develop a website, I am incorporating image preloading using JavaScript. However, I want to ensure that the preload_images() function is not called for users on slow bandwidth connections. In my experience, the main demographic with slow internet spe ...

Steering clear of using relative paths for requiring modules in Node.js

When it comes to importing dependencies, I like to avoid using excessive relative filesystem navigation such as ../../../foo/bar. In my experience with front-end development, I have found that using RequireJS allows me to set a default base path for "abso ...

Are you in the business of building JavaScript hubs?

I have a unique setup where my express server is in charge of handling all routing and session functionalities. I've envisioned a system where logged-in users can connect to distinct "hubs" based on the location of each hub. My idea was to treat each ...

Change the image size as you scroll through the window

While my opacity style is triggered when the page is scrolled down, I am facing an issue with my transform scale not working as expected. Any suggestions on how to troubleshoot this or any missing pieces in my code? Codepen: https://codepen.io/anon/pen/wy ...

Displaying content on a webpage using PHP, AJAX, and HTML

Looking to update my current form setup. I have a basic Form below: <form action="" method="POST"> <input type="button" value="Generate Numbers" onclick="on_callPhp1()"/> </form> Accompanied by this javascript code: <script type="te ...

Learn how to display a tooltip for every individual point on a Highcharts network graph within an Angular

I am currently working on developing network graphs using highcharts and highcharts-angular within my Angular application. I have successfully managed to display the graph with datalabels, but now I need to implement tooltips for each point or node on the ...

Resolving the Issue of Jerky Graphics During HTML5 Canvas Animation

When animating a layer in canvas, the visual quality becomes uneven if there are additional layers present. You can see an example of this by clicking "RUN" on this fiddle: http://jsfiddle.net/Q97Wn/ If I modify this line: opts.percentageIndicator.clearR ...

Display popup depending on the post's identification number

Currently, I'm in the process of integrating Sanity into my blog. Using the json object returned from a query with useState, I managed to display my posts successfully. However, I am now faced with the challenge of populating a React-Modal with the ap ...

Tips for organizing checkboxes in rows horizontally

My question is related to this issue I am trying to arrange my checkboxes in 4 columns horizontally <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> ...

What is the best way to transfer data from a custom method and use it in another method within my constructor function in Javascript?

As I pondered a suitable example, I devised a constructor function centered around precious metals. This function accepts the type of metal and its weight as parameters. Within this constructor, there are two methods: one to verify if the precious metal (g ...