What is the best way to enable or disable a button based on the input value dynamically?

Issue:

In my setup, number inputs and buttons are dynamically created using a v-for loop. The value of the number input, named subExpense, is added to an array called expenseButton[].

Solution Attempt:

I am attempting to disable the dynamically created buttons when the corresponding input field is empty. Specifically, each button should be disabled until its respective number input is filled in.

Implementation:

<div class="buttonFor" v-for="(expense,index) in expenseButton" :key="index">
            <button class="btn btn-primary mx-3" @click="toggle(expense)" :disabled="isDisabled(expense.subExpense)">{{expense.expensesKey}}</button>
            <input v-model="expense.subExpense" type="number" />
</div>

Script Section:

data() {
    return {
      budgetOwner: "",
      myExpense: [],
      expenseButton: [],
      component: "",
      errored: false,
      subExpense: ""
    };
  },
  methods: {
    toggle(expense) {
      console.log(expense.subExpense);
    },
    computed: {
        isDisabled(subExpense) {
          return subExpense.length < 1;
        }
    },
    beforeRouteEnter(to, from, next) {
      axios
        .get("/api/budget", {
          headers: { "Content-Type": "application/json" },
          withCredentials: true
        })
        .then(res => {
          next(vm => {
            if (res.data.budget.length > 0) {
              vm.myExpense = res.data.budget;
              vm.budgetOwner = res.data.name;
              vm.expenseButton = res.data.budget[0].expenses;
              vm.component = "navbar-check";
            } else {
              vm.component = "navbar";
            }
          });
        })
        .catch(err => {
          next(vm => {
            console.log(err.response);
            vm.errored = true;
          });
        });
    }
};

Answer №1

Based on my understanding, you are looking to disable a specific button until the user inputs text into a corresponding text box.

You can achieve this functionality by implementing the following code snippet:

<div id="app">
  <ul class="list">
    <li v-for="item in items">
      <input type="text" v-model="item.text" v-on:keyup="SetAttribute(item)" />
      <input type="button" :disabled="item.text === item.blankCheck" :value="item.value" v-on:click="CheckThis" />
    </li>
  </ul>
</div>

var vm = new Vue({
  el: "#app",
  data: {
    items: [{ text:"", value:"Click", blankCheck:"_blank"}, { text:"Sometext", value:"Click", blankCheck:"_blank"}, { text:"", value:"Click", blankCheck:"_blank"}]
  },
  methods: {
    CheckThis: function() {
      alert('run');
    },
    SetAttribute: function(item) {
      item.blankCheck = '';
    }
  }
});

For a working example, you can view the fiddle here.

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

Alert: when rendering component lists with v-for, ensure they have explicit keys mentioned

I'm facing an issue with my code and getting a warning in the console. Can anyone help me understand how to eliminate this warning? [Vue tip]: <todo-item v-for="todoItem in todos">: component lists rendered with v-for should have exp ...

Update the image links to automatically refresh every half a second based on the values inputted in the text bars

Is there a better and simpler way to define AAAAAAAAAA, BBBBBBBBBB, and CCCCCCCCCC using the links provided in the text bars named chart1, chart2, and chart3? This learning project is being done through Notepad++ for personal use only, with no need to sa ...

Utilizing get requests to manage data in Node.js with MongoDB database integration

I'm a newbie and I have a question.. How do I synchronize the mongoose query with the JSON response? The current code is returning empty values because the query finishes executing later. What would be the best way to handle this issue? router.route( ...

The use of JavaScript variables for classes or IDs

I am currently working on a JavaScript code in a .js file where adding a class to an HTML element, like 'open-product', triggers the opening of a product popup. $('.open-product').on('click', function(){ showPopup($(& ...

What is the best way to transfer variables and functions between JavaScript and Python seamlessly?

I am in the process of building a website using HTML, CSS, and JavaScript, and I am in need of an AI-powered chatbot. I have a Python file that contains the necessary logic for the chatbot (AI, NLTK). Inside the Python file, there is a function called "res ...

Incorporating Stencil modules into your Ionic Vue projects

When integrating Stencil with Vue in the documentation, it is mentioned that: To use the custom element library within a Vue app, you must modify the application to define the custom elements and inform the Vue compiler which elements to ignore during co ...

MUI: Autocomplete cannot accept the provided value as it is invalid. There are no matching options for the input `""`

https://i.stack.imgur.com/KoQxk.png Whenever I input a value in the autocomplete component, an unresolved warning pops up... Here's how my input setup looks: <Autocomplete id="cboAdresse" sx={{ width: 100 + " ...

How to sort an array of multiple objects in AngularJS based on a specific property

Having an array of multiple objects: { "option_12": { "id": "0", "name": "6 x 330ml", "price": "0.00" }, "option_14": { "id": 1, "name": "12 x 330ml", "price": "2.00" }, "option_17": { "id": 1, ...

GET request being blocked by iframe

I recently encountered a problem with my hosted payment page that is loaded within an iframe. After the transaction is complete, the payment provider attempts to use a URL specified by us in the iframe to navigate away from it and perform any necessary ac ...

Having trouble retrieving the contents of a <div> tag within a JavaScript function

Javascript Code In First ContentPlaceHolder :- <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> <script type="text/javascript" > function PrintElem(elem) { alert(elem); Popup($(elem).html()); } ...

Using JQuery to duplicate text and insert it into a textarea

Looking for a more efficient way to achieve the same functionality with my JavaScript function. Currently, it copies text from a hidden span and inserts it into a textarea on a website after a few clicks. Any ideas on how to streamline this process? It&apo ...

Using NicEdit for uploading to your personal server

I'm having trouble uploading images using the NicEdit WYSIWYG editor on my own server. When I click on the upload image button, it redirects me to another site where I can upload the image: imgur dot com You can find a demo of this here: However, I ...

Tips for resolving the GOOGLE_APPLICATION_CREDENTIALS issue when deploying Firebase hosting using GitHub CI/CD automation

I am currently working on a Vuejs project hosted on Firebase hosting with GitHub actions for CICD. I encountered the following error during deployment to Firebase. Below is my build-and-deploy.yml code: - name: Deploy to firebase uses: w9jds/<a hre ...

What is the most efficient method in React for displaying an array as a table and wrapping every set of five elements with a <tr> tag?

Currently, I am working on rendering a table in React from an array of objects. My approach involves mapping the array to create table elements as shown below: var objects = response.data; var arrayOfTableElements = [] ...

Modify selection from an Array in a non-systematic way

I am currently working on a flashcard system that randomly selects a value from an array. However, I also want to implement a button with the ID "switchBtn" to change the random value being displayed. Is there any way to achieve this functionality? Here ...

In the event that the p-value is equal to a non-functioning

Just started delving into the world of JavaScript and jQuery. Take a look at the code snippet below: $(document).ready(function(){ $("#p1").click(function(){ var input = document.getElementById("p3"); if (input.value == "Hi ...

Creating a Vue.js transition that causes an icon to slide upwards along with an expanding panel

My goal is to implement a panel that expands from the bottom of the screen when an icon is clicked. I am utilizing Vue.js transition for animating the panel sliding in from below. However, I encountered an issue where the icon instantly jumps to its final ...

Validation of JSON Failed

Encountered a 400 Bad Request error while attempting to POST an answer using Postman, it appears to be a validator issue. Despite multiple attempts, I have yet to resolve this issue. Below are details of the JSON data being sent in the POST request along w ...

Implementing dynamic page loading with ajax on your Wordpress website

I'm currently facing an issue with loading pages in WordPress using ajax. I am trying to implement animated page transitions by putting the page content into a div that I will animate into view. However, my current logic only works correctly about 50% ...

Is it possible to include a module-level controller within a directive?

I am currently navigating the complexities of controllers, modules, and services in Angular JS. In my attempt to integrate a controller into my directive, I faced an issue. The controller I intend to reference belongs to the same module as the directive, ...