Vue3 - Managing the Enabling and Disabling of Text Input and Checkbox Based on Input Number

<div class="container-body" v-for="index in 10" :key="index">
    <div class="container-content"></div> 
    <div class="container-content">
        <input :id="'Row'+index+'-input1'" type="text">
    </div> 
    <div class="container-content">
        <input :id="'Row'+index+'-input2'" type="text" class="disabled">
    </div> 
    <div class="container-content">
        <div class="custom-control custom-checkbox">
            <input :id="'Row'+index+'checkbox'" class="form-check-input" type="checkbox" disabled>
        </div>
    </div> 
    <div class="container-content delete">
        <img/>
    </div>
</div>

There will be a total of 10 input rows generated using v-for loop.

My goal is to make Row1-input2 and Row1-checkbox enabled when the user enters a number in Row1-input1. This should not impact the other 9 rows. Additionally, clicking on the delete section should clear the entire row value.

I am uncertain about the best approach in Vue.js to accomplish this task. Should I create 10 separate data variables and store the value on keyup events, then use them to bind with :disabled? Or are there any Vue.js methods that could simplify this process?

Answer №1

In my opinion, the most effective strategy would involve developing a component for a single line, where all the necessary logic for managing a single instance can be consolidated. Subsequently, multiple instances of this component can be created as needed.

Below is a sample implementation for your specific task, assuming I have correctly grasped the requirements:

const {
  computed,
  createApp,
  ref,
} = Vue;

const defaultRowValue = {
  input1: '',
  input2: '',
  checkbox: false
}

const customRow = {
  props: ['index', 'modelValue'],
  emits: ['update:modelValue'],
  setup(props, {
    emit
  }) {

    const model = computed({
      get: () => props.modelValue,
      set: (val) => {
        emit('update:modelValue', val)
      }
    })

    const disable = computed(() => model.value.input1);

    const clearRow = () => {
      model.value = { ...defaultRowValue
      };
    }

    return {
      model,
      clearRow,
      disable,
    }
  },
  template: `
  <div class="container-body">
      <div class="container-content"></div>
      <div class="container-content">
        <input :id="'Row'+index+'-model.input1'" type="text" v-model="model.input1">
      </div>
      <div class="container-content">
        <input :id="'Row'+index+'-model.input2'" type="text" v-model="model.input2" class="disabled" :disabled="!disable">
      </div>
      <div class="container-content">
        <div class="custom-control custom-checkbox">
          <input :id="'Row'+index+'checkbox'" class="form-check-input" type="checkbox" :disabled="!disable" v-model="model.checkbox">
        </div>
      </div>
      <div class="container-content delete">
        <button @click="clearRow">delete</button>
      </div>
    </div>
  `
}

const app = createApp({
  data() {
    return {
      rows: []
    };
  },
  mounted() {

    // Generate sample data
    for (let i = 0; i < 10; i++) {
      this.rows.push({ ...defaultRowValue
      })
    }
  }
})

app.component("custom-row", customRow);

app.mount('#app');
#app {
  display: flex;
}
<script src="https://unpkg.com/vue@next"></script>
<div id="app">
  <div>
    <custom-row v-for="(_, key) in rows" :key="key" :index="key" v-model="rows[key]"></custom-row>
  </div>
  <pre>
    {{rows}}
    </pre>
</div>

Answer №2

You must identify the individuality within your inputs.

As mentioned earlier, you can create a :value or v-model for each input.

Then combine each string with an index to generate a unique input.

When doing this, ensure that the v-model of the input is returned with an array type and not a string type.

This is necessary because the concatenation requires a string and an index.

Here is an example of how to use v-model:

For input 1

v-model="row.input[index+'-input1']"

For input 2

v-model="row.input[index+'-input2']"

Now, you will have access to your row inputs.

You can then utilize them with the disabled and delete functions.

Demo

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

The template for a Vue dynamic component refuses to function properly with a promise

<template> <component :is="myComponent" /> </template> <script> export default { props: { component: String, }, data() { return { myComponent: '', }; }, computed: { loader() { ...

Tips for showcasing images consistently in a V-Card with uniform sizes

Hey there, I'm facing a bit of a challenge that I can't seem to crack. Apologies for not sharing my entire code. So here's the problem: I'm working on this: <v-card> <v-img :src=“{{person.png}}”</v-img> <v-card& ...

Vue Cli 3: customization of output directory paths

I am looking for assistance in setting up the output paths for my final build. Here is what I need: Although my Vue project follows the default structure, the output paths are located outside this structure: Output HTML file: ../main/resources/ Output o ...

Best practice for incorporating Bootstrap into Webpack

Greetings everyone, I've been experimenting with Bootstrap for Webpack, but I've hit a roadblock. After reading numerous blog articles, I found that they either rely on the outdated 'bootstrap-webpack' plugin from 7 months ago (which d ...

Combining several meshes in ThreeJS while maintaining distinct materials

I seem to be facing a dilemma. I am attempting to consolidate several meshes into one in order to optimize draw calls. Each mesh I have comes with its own unique material, whether it be color or texture. Below is the snippet of code I have been working on ...

Is there a way to use an Angular expression inside an HTML document to determine if a variable is a boolean type?

I'm working with an element in my HTML where I need to determine the type of a variable, specifically whether it's a boolean or not. <button process-indicator="{{typeof(button.processIndicator) === 'boolean' ? 'modalProcess&apo ...

Permitting various valid responses for questions in a multiple-choice test | Utilizing Angular.js and JSON

As a beginner in this realm, I must apologize if my query seems naive. I recently crafted a multiple-choice quiz using HTML, CSS, JavaScript (angular.js), and a JSON data file following a tutorial I stumbled upon. The outcome pleased me, but now I am face ...

Modifying dat.gui to reflect changes made to the selected object

check out this working code I am currently exploring ways to update or refresh dat.gui in order to reflect the changes I make to my selection. My main objective is to generate random cubes and then manipulate a single cube by rotating, scaling, changing p ...

Troubleshooting: Issue with displaying PHP data on an AngularJS table using JSON through jQuery AJAX

I've been encountering an issue while trying to display data from a database on my HTML page using Angular and JSON. Despite the browser being able to read the database, it fails to show the data. Can anyone shed some light on why this might be happen ...

There seems to be an issue with the way Meteor and React are displaying data

Having trouble displaying paint data in my code - all I see is [object,object]. Tried using .toString() without success. Any assistance would be appreciated. I understand that this indicates objects inside arrays but unsure how the array is generated or h ...

Personalized Angular dropdown menu

Recently, I've started delving into angularJS and I'm eager to create dropdowns and tabs using both bootstrap and angular. Although there is a comprehensive angular bootstrap library available, I prefer not to use it in order to gain a deeper und ...

Exploring an array to retrieve a specific value

Can someone assist me? I am looking to create a JavaScript function that follows the structure of the code example below. Unfortunately, I do not have enough programming skills to develop a functional solution from scratch. The goal is to input a value, ...

What is the best way to iterate through an ID using jQuery?

After pulling the list of doctors in my area from the database and displaying it on my webpage, I now want to load each doctor's "About" content inside a Bootstrap modal. I added an "about" column within the same database table where the doctors' ...

What is the best way to implement page navigation within Nuxt?

Is there a way to efficiently paginate and display comments from this particular API? Should we retrieve the entire object and use slice() for pagination, or is there a specific method for fetching comments in chunks for a single page? Furthermore, how c ...

Implementing the insertion of a <div> element within an input field using jQuery

<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></scr ...

Cannot retrieve the <li> element from the array

I am trying to display list items inside an ordered list (ul) from an array, but I am facing issues with it. Whenever I try to map through the array, I encounter an error message saying Map is not a function. Any assistance on resolving this would be hig ...

Focusing in on a PARTICULAR SECTION of the picture

My website has a unique concept - comparing two articles side by side. One of the articles is mine, while the other is displayed alongside it. To capture entire pages for comparison, I utilize Google's GoFullPage feature to take screenshots. The goa ...

The method mongoose.connect() is not defined

Having a bit of trouble connecting to my MongoDB using Mongoose - keep getting this error. const { mongoose } = require('mongoose'); const db = 'dburl.com/db' mongoose.connect(db, { useNewUrlParser: true }) .then(() => console ...

What could possibly be causing my code to execute multiple times?

Within my code, I have the following function that is triggered when the document is ready: $('#file_upload_form').submit(function(){ // show loader [optional line] //if(document.getElementById('upload_frame') == ...

Is the XPath in Selenium executed against the Document Object Model (DOM) or the HTML file

Currently, I am in the process of developing a library for analyzing webpages. My approach involves using Selenium to access elements on a webpage through xpath. I have been contemplating replacing Selenium with an offline xpath tool. However, upon furthe ...