Obtaining the current value with each keystroke

While working with vue.js, I'm building a table that contains an input field called quantity. However, when I start typing the first word, it shows 'empty' on the console.

If I type 3, it displays empty; and if I type 44, it prints 4. I am handling the event using v-on:keypress, but I can't figure out what's going wrong here.

var app = new Vue({
  el: "#app",
  data: {

    invoice_products: [{
      product_no: '',
      product_name: '',
      product_price: '',
      product_qty: '',
      line_total: 0
    }]
  },

  methods: {
    calculateLineTotal(invoice_product) {
      console.log(invoice_product.product_qty)
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.6/vue.js"></script>
<div id="app">

  <table>
    <thead>
      <tr>

        <th>Quantity</th>
        
      </tr>
    </thead>
    <tbody>
      <tr v-for="(invoice_product, k) in invoice_products" :key="k">

        <td>
          <input class="form-control text-right" type="number" min="0" step=".01" v-model="invoice_product.product_qty" v-on:keypress="calculateLineTotal(invoice_product)" />
        </td>

      </tr>
    </tbody>
  </table>
</div>

Answer №1

The recommended event handler to use is keyup.

KeyPress, KeyUp, and KeyDown can be compared to, respectively: Click, MouseUp,, and MouseDown.

  1. Down occurs first
  2. Press happens second (when text is entered)
  3. Up takes place last (when the text input is complete).

var app = new Vue({
  el: "#app",
  data: {

    invoice_products: [{
      product_no: '',
      product_name: '',
      product_price: '',
      product_qty: '',
      line_total: 0
    }]
  },

  methods: {
    calculateLineTotal(invoice_product) {
      console.log(invoice_product.product_qty)
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.6/vue.js"></script>
<div id="app">

  <table>
    <thead>
      <tr>

        <th>Quantity</th>
        
      </tr>
    </thead>
    <tbody>
      <tr v-for="(invoice_product, k) in invoice_products" :key="k">

        <td>
          <input class="form-control text-right" type="number" min="0" step=".01" v-model="invoice_product.product_qty" v-on:keyup="calculateLineTotal(invoice_product)" />
        </td>

      </tr>
    </tbody>
  </table>
</div>

Answer №2

The issue you are facing is that the keypress event triggers when the key is pressed, before it is processed in the input field. This allows your event process function to capture and potentially filter out the key. As a result, the field does not display the correct result immediately because it has not yet registered the keypress.

To resolve this issue, consider modifying your logic to capture the keyup event instead. This event is triggered after the key has been entered in the focused field.

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

Why is my Vue view not being found by Typescript (or possibly Webpack)?

npx webpack TS2307: Cannot locate module './App.vue' or its corresponding type declarations. I am currently utilizing webpack, vue, and typescript. My webpack configuration is pretty basic. It uses a typescript file as the entry point and gener ...

Preventing Angular button click when an invalid input is focused out

Here is a Plunker link http://plnkr.co/edit/XVCtNX29hFfXtvREYtVF?p=preview that I have prepared. In this example, I've asked you to: 1. Enter something in the input field. 2. Click directly on the button without interacting with any other element. ...

Authentications for live search within Elasticsearch 8.x

I am looking to utilize reactivesearch without relying on appbase.io, and instead opting for a self-hosted Elasticsearch setup using Docker. It appears that Elasticsearch 8.x has introduced a new concept of authorization. I have set up ES and Kibana throu ...

Executing a JavaScript code in a Python webdriver: A step-by-step guide

Using Selenium 2 Python webdriver: I encountered an issue where I needed to click on a hidden element due to a hover effect. In search of solutions to unhide and select the element, I came across the following examples: Example in Java: JavascriptExecut ...

Utilize Postman to send a JSON body in a POST request to trigger a stored procedure on Microsoft SQL Server

I need to send a JSON request using the Postman app, utilizing the POST method to retrieve data. My boss, who is overseeing my training, assigned me this task. I've scoured the web for a week but haven't found a solution yet. Initially, I sugges ...

Creating a conditional interface based on props in TypeScript: A step-by-step guide

What is the most effective way to implement conditional props in a component that can be either a view or a button based on certain props? Let's take a look at an example called CountdownButtonI: class CountDownButton extends Component<CountdownBut ...

How can I create an input field that comes with a preset value but can be updated by the user with a different name?

I am in need of a solution that will enable a user to update text on a webpage dynamically. I have been unable to find any information on how to achieve this. Is there anyone aware of a method to implement this feature? Perhaps a library or utilizing Vue ...

FireFox is unresponsive to OPTIONS requests

I have a webpage that is accessed through HTTP. The client-side code is making AJAX requests for authorization to the same domain, but using HTTPS, which causes CORS issues. When using FireFox, the request looks like this: // domains and cookies are chang ...

Can you clarify the functionality of this loop? I am having trouble grasping how it produces the final result

Seeking clarification on the highlighted section] I need assistance in understanding how the use of "text" helps to print the following literal. ...

Refresh the texture mapping within ThreeJS

Hey there! Just wanted to share that I was able to find a solution by using mesh.material.map.image.src = texture; Here was the original question: I'm working on a ThreeJS project and I'm trying to change the texture on a mesh. Unfortunately, I ...

Encountering issues with Vue-Router functionality after refreshing page in Laravel-6

Can someone explain what is going on here? Whenever I refresh my web browser, it no longer recognizes the route. ...

Retrieve the value of an attribute within a controller function that is not a directive

Here is some HTML content, <button data-href="helloworld">Show href Value</button> And here is some Javascript content, $("body").on('click', 'button', function(){ console.log($(this).attr("data-href")); }); When exe ...

Incorporating Angular to dynamically fetch data through AJAX and fill in content post-page render

As a backend API developer diving into AngularJS (version 1) for the first time with my current project, I have encountered a scenario that requires me to fetch server-side content dynamically post-render. The page is set up with ng-app="app" in the <ht ...

In JavaScript, the event.defaultPrevented property will never be set to true

I've been experimenting with events in my script, but I'm struggling to understand the functionality of event.preventDefault()/event.defaultPrevented: var e = new Event('test'); e.defaultPrevented; > false e.preventDefault(); e.d ...

Update button text in real-time using JavaScript

I am currently working on a dropdown list that contains 5 elements displayed inside a button when pressed. I want the button to show a default text "Filter by:" before displaying the selected tab value. Additionally, I need the caret symbol to be visible. ...

WebSocket connection was unsuccessful. Switching to Comet and resending the request

I have been utilizing the Atmosphere framework 2.0.0.RC5 to expand my web application with websocket capabilities and encountered a perplexing error 'Websocket failed. Downgrading to Comet and resending' that I can't seem to resolve. To sta ...

Steps for adding a div to a Vue template

When working with my template, I utilize a for loop to iterate through data entries. <tr v-for="entry in filteredData"> <td> @{{ entry.position}} </td> <td :class="addNewElement(entry.value)"> </td> <td> ...

Adding a .PHP File to Two Separate DIVs

I am using wordpress to create a custom theme. I'm interested in placing all the content from my slider.php file inside a div box on my index.php page. How would I go about doing this? SLIDER.PHP <div class="slider"> // All the image tags wit ...

How can I loop through JSON in AngularJS to populate fields without knowing the key value?

Here is the data structure that I'm working with: { "0": { "keyword": "flower", "short_desc": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "pt_value": "5" }, "1": { "keyword": "tree", "short_desc": "Lorem ipsum dolor sit amet, consecte ...

What is the best way to conceal the scrollbar in a v-textarea?

Is it possible to hide the scrollbar in a v-textarea element? Although hiding the scrollbar works on a simple textbox, attempting the same method on a v-textarea does not yield the desired results: <v-textarea class="hide-scrollbar"/> < ...