Prevent a dynamically generated text input from being used if it exceeds a specific character limit in VUE.JS

I am currently working on a Vue template that dynamically creates Bootstrap text inputs. The goal is to allow the user to retrieve the values onSubmit from these inputs.

One requirement I have is to disable an input if the length of the text exceeds 10 characters. I have been struggling with this problem since yesterday and any assistance would be greatly appreciated.

<script>
export default {
  data() {
    return {
      items: [],
      inputsAmount: 0,
      form: [],
      disableInput: false
    };
  },
  methods: {
    addInput() {
      let theNumberOfInputs = this.inputsAmount++;
      if (theNumberOfInputs < 8) {
        this.items.push({ value: theNumberOfInputs });
      } else {
        return;
      }
    },
    getFormsInputs() {
      let theFormsInputs = {}, theQuestionnaire = [], overLimit = false;
      console.log(this.form);
      if (this.form.length) {
        this.form.forEach((inputValues, iInputValues) => {
          theFormsInputs["answer" + (iInputValues + 3)] = inputValues;
          overLimit = this.checkInputLenght(inputValues);
        });
      }
      console.log(overLimit);
      if(!overLimit){ theQuestionnaire.push(theFormsInputs); }
      return theQuestionnaire;
    },
    submit() {
      const theQuestionnaire = this.getFormsInputs();
    },
    checkInputLength(pInputValues) {
      if (pInputValues.length > 80) {
        console.log("Limited Exist");
        this.disableInput = true;
        return true;
      }
    }
  }
};
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
  <div>
    <b-container>
      <b-row class="mt-2" v-for="(item, iItem) in items" :key="iItem">
        <b-form-input v-model="form[iItem]" placeholder="Please, type your answer."></b-form-input>
      </b-row>
      <button @click="addInput()">Test</button>
      <button @click="submit()">Submit</button>
      <button @click="resetState()">Reset</button>
    </b-container>
  </div>
</template>


<script>
//TODO CHECK FOR HOW TO PASS DATA

Answer №1

Make sure to set up the disabledInputs: [] array within your reactive data section

data() {
    return {
      items: [],
      inputsAmount: 0,
      form: [],
      disabledInputs: []
    };
  },

Include

:disabled="disabledInputs.includes(`input_${iItem}`)"
in your b-form input attributes

<b-row class="mt-2" v-for="(item, iItem) in items" :key="iItem">
        <b-form-input v-model="form[iItem]" placeholder="Please, type your answer." :disabled="disabledInputs.includes(`input_${iItem}`)"></b-form-input>
</b-row>

Remember to pass the index to your check method

this.form.forEach((inputValues, iInputValues) => {
  theFormsInputs["answer" + (iInputValues + 3)] = inputValues;
  overLimit = this.checkInputLenght(inputValues, iInputValues); //here
});

Add the index to the disabled array

checkInputLenght(pInputValues, idx) {
  if (pInputValues.length > 10) {
    this.disabledInputs.push(`input_${idx}`); // add to array
    return true;
  }
},

Take a look at this working example:

https://codesandbox.io/s/silly-forest-pmxd8?file=/src/App.vue

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

Specify the return type based on specific parameter value

I'm facing a situation where I have two definitions that are identical, but I need them to behave differently based on the value of the limit parameter. Specifically, I want the first definition to return Promise<Cursor<T>> when limit is g ...

What is the best way to access the following element of an array within a for..of loop with an if statement in Javascript?

Need help with creating a word filter that checks if index 1 is 'dog' and index 2 is 'cat' in an array. What should be checked in the next index for 'word'? let textContainer = ['bird', 'dog', 'cat& ...

There are certain lines of JavaScript/Node.js code that are failing to execute

app.get is not being executed. I have also attempted to include app.listen(3000). My goal is to retrieve the parameter passed from the first web page. This code is designed to fetch parameters sent by another web page and then construct a MySQL query and ...

Using a Vue.js directive in a template

After studying the example at https://vuejs.org/examples/select2.html, I attempted to create a reusable component for future use. Regrettably, my code is not functioning as expected. Here is the HTML structure: <template id="my-template"> <p&g ...

Is there a way to detect changes in a Service variable within an Angular component?

One of my components contains a button that activates the showSummary() function when clicked, which then calls a service named Appraisal-summary.service.ts that includes a method called calc(). showSummary(appraisal) { this.summaryService.calc(appraisal ...

Creating a dynamic form in Django that allows users to input text and insert images using AJAX technology

My goal is to develop a website for creating articles that go beyond the standard models.TextField setup commonly used with Django. I want users to have the ability to add an arbitrary number of text and image fields to their articles, while also ensuring ...

Exploring the world of cookie security with SameSite and Secure features in ExpressJS

Despite having the specified settings on my express application, a warning keeps appearing in the console. Has anyone encountered this error before? I found some information related to it here: https://github.com/expressjs/express/issues/3095 The version ...

What is the method for displaying a file using a binary string as input?

Is there a way to display a PDF file from a binary string on a web browser? I know that for image files, we can use atob() and then <img src="data:image/png;base64,... But what about PDF files? Is there an equivalent method or syntax like ReadItAs("cont ...

The functionality of the Regions plugin in wavesurfer.js appears to be completely nonfunctional

I've been attempting to utilize the Regions plugin from wavesurfer.js, but unfortunately, it's not functioning as expected. Despite trying various methods suggested on different websites, I have yet to achieve success. Below is the snippet of c ...

I am facing conflicts between vue-tsc and volar due to version discrepancies. How can I resolve this problem?

My vsCode is alerting me about an issue: ❗ The Vue Language Features (Volar) plugin is using version 1.0.9, while the workspace has vue-tsc version 0.39.5. This discrepancy may result in different type checking behavior. vue-tsc: /home/tomas/Desktop/tes ...

Remove option from MUI Autocomplete after it has been selected

I am currently utilizing a Material-UI Autocomplete component. To avoid users selecting the same element twice, resulting in duplicate ID numbers, I want to remove the element from the dropdown entirely. For instance, if "Shawshank Redemption" is selected ...

I'm curious, are there any html rendering engines that can display text-based content using curl-php?

When utilizing PHP cURL to interact with webpages, I often find myself needing to use regular expressions if the page contains AJAX and JavaScript elements. Does anyone have any recommendations for rendering HTML pages and extracting the text-based render ...

What alternative methods can be used to render a React component without relying on the ReactDOM.render

Can a React component be rendered simply by referencing it with its name? For example: <div> <MyComponent/> </div> In all the tutorials and examples I've seen, ReactDOM.render function is used to render the component onto the ta ...

Switch the checked status of an input dynamically using jQuery function

It seems like I might be overlooking something quite obvious, but I can't figure out why this jquery function is behaving inconsistently. HTML: <label id="income_this_tax_year"> <div class="left"> <p>Have you had Self-Employm ...

Mist Conceals Celestial View (THREE.JS R76)

I have a cylindrical camera setup with fog to hide the end of the tube. However, I am trying to make the skybox visible through the alpha map sides of the cylinder. The current issue is that the fog is blocking the visibility and I'm looking for a sol ...

Vue looping through an object containing arrays

I am facing an issue with my code where I need to iterate over multiple objects with arrays, but no return data is being displayed. Can someone please help me with my code? Here is a sample of JSON data retrieved from an API: "sections": [ ...

Drop your friend a line, I'm curious about the Javascript API

As a developer hailing from the Republic of Korea, I am currently in the process of creating websites that are based on Facebook and Twitter. I am interested in utilizing a JavaScript API that allows me to send messages to friends. Initially, I considered ...

Bring in properties from a separate file in Vue3

Currently, I am utilizing Vue3 along with the options API. Within my setup, there are various Vue components that rely on a shared prop defined as: exercise: { type: Object as PropType<Exercise>, required: true, }, To streamline this pro ...

Guide for deploying a Vue.js - Express app on a local Ubuntu machine

Can anyone provide guidance on deploying a full stack Vue-Express application to a local Ubuntu server? I've been searching online but haven't found clear instructions. Any help would be greatly appreciated. ...

Populating a clickable list and form with a complex JavaScript object

I have a code snippet that takes an unstructured String and parses it into a JavaScript object. My next step is to integrate it into a web form. You can check out the demo here. The demo displays the structured object hierarchy and showcases an example of ...