Member Avatar for Zagga

Hi folks,

It's a bit unusual for me to post in the javascript forum but I'm after a bit of assistance if possible.

The scenario:
I have a form with text input box for a user to enter a 'quantity' in. This can be anything from 1 to 99.
When a user enters a 'quantity' it should be multiplied by a set 'price' (£2) and the total should be displayed in a 'total' box.

Scenario example:
A user enters a quantity of 5, this is multiplied by the set price and £10 is displayed in the total box.

Current state of play:
I can get this to partly work with an onchange trigger on the quantity box that fires a function to calcutate the new total and display it on the form. The total changes correctly whenever focus leaves the quantity box.

The problem:
If a user enters a quantity then clicks on the submit button before focus has left the quantity box, the total does change but the user doesn't get a chance to see the updated price (to confirm it is ok) before the form is submitted.

What I tried:
I thought about disabling the submit button if focus is in the quantity box but this reduces usability quite a bit.
I considered forcing the focus to leave the quantity box once a user has entered 2 digits, but this doesn't help if the quantity is a single digit.

The question:
Is there a way, without using AJAX if possible, to update the total as the user types into the quantity box? Or any other possible solutions?

Example code:

<script type="text/javascript">
function ReprintPrice(){
    var theQuantity = document.getElementById("quantity").value,
    newPrice = (theQuantity * 2);
    newPrice = parseFloat(newPrice).toFixed(2);

<input id="quantity" name="quantity" onchange="ReprintPrice()" maxlength="2" size="1" value="0" type="text" />
<span id="entrycost">&#163;0.00</span>
<input type="button" value="Submit" onclick='alert("Form Submitted before I got a chance to see the updated price")' title="submit" />

Any help in this would be greatly appreciated.

Have you tried using the onkeydown or onkeyup event?

Member Avatar for Zagga

onkeyup works perfectly. Thanks pritaeas!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.