3

When a field in my form gets focus, I'd like a javascript function to be called that calculates a value for that field without my putting in a specific button to do that.

Is this possible without causing the form to reload?

I have thought about making the Amount field read-only, and some other ways of doing this, but I'm looking to see if changing the Quantity field could cause the Amount field to change either using onchange in the Quantity field or onfocus in the Amount field.

Purchase Tickets<br>                
<script type="text/javascript" language="JavaScript1.2">
<script type="text/javascript" language="JavaScript1.2">
document.write(
'<form name="InvGenPayTickets" action="'+PostURL+'" 
onsubmit="return validateForm();" method=GET>');
</script>

<input type=hidden name="TplURL" value="GenPayCCInfo.html">
<input type=hidden name="CancelURL" value="Ooopsie.html">
<input type=hidden name="SuccessURL" value="Joanie.html">

<input type='hidden' name='TransDesc' id='TransDesc' 
value="$_POST['TransDesc']; ?>" />

<input type='text' name='Quantity' id='Quantity' /> <br />
Amount<br />
$<input type='text' name='Amount' id='Amount' />
<input type="submit" value="Next">
<br>
</form>

Edit:

Here is the function that won't update. It is called if I use

<input type='text' name='Quantity' 
     id='Quantity' onchange="return retTotalAmt();" /> 

but the Amount field does not update. I am not able to update using a calc button either.

<script type="text/javascript" language="JavaScript1.2">    
    function retTotalAmt()
    {
        alert("Got here.");
        var total_amt 
            = (document.getElementById('Quantity').value * ticketCost) 
                + DonationAmount;    
        document.getElementById('Amount').value = total_amt;
    }    
</script>

Per request in comments:

&nbsp;
<input type='text' name='Quantity' 
    id='Quantity' onchange="return retTotalAmt();" /> 

Edit -- Show Problem

<script type="text/javascript" language="JavaScript1.2">
var ticketCost = 40.00;

function EnterPage()
{
var currentTotalAmount = DonationAmount + ticketCost;
//DonationAmount moved up to ticketCost's scope fixed problem.
var DonationAmount = <?php echo($_POST['DonationAmount']); ?>;

document.getElementById('DonationAmountField').value = DonationAmount.toFixed(2);
document.getElementById('Quantity').value=1;
document.getElementById('Amount').value = currentTotalAmount.toFixed(2);

return;
}

Lior
  • 2,531
  • 1
  • 15
  • 15
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
  • Yes, you would use the `focus` event. see [here](http://stackoverflow.com/questions/3763080/javascript-add-events-cross-browser-function-implementation-use-attachevent-add) for a cross-browser way to attach events to an element. – Shmiddty Sep 12 '12 at 16:48

6 Answers6

1

Without using jquery:

<input type='text' name='Amount' id='Amount' onfocus="amountOnFocus();" />

Javascript:

function amountOnFocus() {
    amountField = document.getElementById('Amount');
    //Do calculations
    amountField.value = resultOfCalculations;
}

If you wanted, you could also put a change event listener on the Quantity input so it will calculate when the value of that textbox changes.

EDIT: This onchange event works for me:

Markup:

<input type="text" id="txtChangeMe" onchange="txtChangeMeOnChange();" />

Javascript:

<script type="text/javascript">
    function txtChangeMeOnChange() {
        alert('changed');
    }
</script>
Dave Zych
  • 21,581
  • 7
  • 51
  • 66
  • I can't get the onchange to fire. I added to the Quantity input, and no luck. I'll go try the focus solution. – octopusgrabbus Sep 12 '12 at 16:59
  • What constitutes a form seeing a change? Is it losing focus? – octopusgrabbus Sep 12 '12 at 17:09
  • The `onchange` and `focus` events are only for form fields. I don't think there's a way to track all changes in a form without using `JQuery`. – Dave Zych Sep 12 '12 at 17:15
  • These two fields are in the form. Quantity and Amount. I've added the javascript function that won't fire by editing the original post. @DaveZych your little test did fire, but my function won't. That's why I edited the post to put the non-firing function in. – octopusgrabbus Sep 12 '12 at 17:21
  • I see an error in your javascript. You are attempting to multiply the `Quantity` input element times your ticket cost. You need to get the value by doing `document.getElementById('Quantity').value`. I don't think that is the source of your issue though. Can you post the markup for the Quantity input? – Dave Zych Sep 12 '12 at 17:28
  • Your markup looks correct, and I see that you say it fires, correct? Check my comment above - You're attempting to multiple the Quantity element by the ticket cost. You need to get the value of the Quantity input and multiply that. – Dave Zych Sep 12 '12 at 17:43
  • Quantity added, and .value added to GetInputByID. – octopusgrabbus Sep 12 '12 at 17:51
  • I see no issue with your code, other than the `ticketCost` and `DonationAmount` variables. Where are those declared? Are they in the scope of your `retTotalAmt` javascript function? – Dave Zych Sep 12 '12 at 17:58
  • I moved DonationAmount to make it a global variable. That did it. Thanks. – octopusgrabbus Sep 12 '12 at 18:01
1

I'm not quite sure what additional information you need, as you seem to be aware of all the ingredients for making this happen: You know that you want to detect an event, you know that you need to call a function, so I'm hoping I haven't missed something about what you're asking. I'm going to assume that you just need to know how to tie all these parts together.

The simplest example might be:

<input type="text" id="Quantity" value="10" onchange="document.getElementById('Amount').value = parseInt(document.getElementById('Quantity').value,10) * 10.0;" />
$<input type="text" id="Amount" value="100" />

though it's worth noting that this does not follow best-practices, which would involve binding an event listener separately.

On the off-chance that you accidentally typed "button" when you meant "field", I will also mention that you can update any other element's innner HTML with the ''innerHTML'' attribute, eg:

<input type="text" id="Quantity" value="10" onchange="document.getElementById('Amount').innerHTML = parseInt(document.getElementById('Quantity').value,10) * 10.0;" />
$<span id="Amount">100</span>

Of course, you can define the actual logic elsewhere, and just use ''onchange="yourFunction();"'' instead of putting everything inline, as well.

I know you mentioned "onchange" and "onfocus", though personally I tend to prefer "onkeyup", so that values will change as the user is typing.

Apologies if I've completely missed the point in your question.

Will Palmer
  • 5,742
  • 1
  • 26
  • 33
0

Sure. Use something like this which will fire when quantity change:

$("#Quantity").change(function(){
    // perform your calculations here
};

This requires the jQuery framework.

Clay Garrett
  • 1,023
  • 8
  • 11
0

Do you have access to jQuery? If not then you would have to bind an change event to your "quantity" input element to listen for a change of its input. Then you would simply need to modify the contents of the "amount" input.

https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener

var el = document.getElementById("Amount");
el.addEventListener("change", changeAmount);

function changeAmount(){
  var quantity = document.getElementById("Quantity");
  quantity.value = "SET YOUR VALUE";
}
Chase
  • 29,019
  • 1
  • 49
  • 48
0
function calcPrice()
{
 ....
}

<input type='text' name='Quantity' id='Quantity' onchange='calcPrice();'/>
<input type='text' name='Amount' id='Amount' onfocus='calcPrice();'/>
enhzflep
  • 12,927
  • 2
  • 32
  • 51
0

Try this solution

Html

 <div class="form-group row">
            <label for="inputQty" class="col-sm-4 col-form-label">Quantity</label>
            <div class="col-sm-8">
                <input onkeyup="CalculateItem();"  onkeydown="CalculateItem();" onchange="CalculateItem();" onfocus="CalculateItem();" value="1" type="number" step="1" min="1" max="9999999" class="form-control" id="inputQty" required>
            </div>
        </div>

        <div class="form-group row">
            <label for="inputPrice" class="col-sm-4 col-form-label">Price</label>
            <div class="col-sm-8">
                <input onkeyup="CalculateItem();"   onkeydown="CalculateItem();" onchange="CalculateItem();" onfocus="CalculateItem();" type="number" step="0.1" min="1" max="9999999"  class="form-control" id="inputPrice" required>
            </div>
        </div>
  <div class="form-group row">
            <label for="inputPriceNoVat" class="col-sm-4 col-form-label">Price (no VAT)</label>
            <div class="col-sm-8">
                <input readonly type="text" class="form-control" id="inputPriceNoVat">
            </div>
        </div>

JS

 <script type="text/javascript">
            function CalculateItem()
            {
                try {
                    let inputPriceNoVat = $('#inputPrice').val() * $('#inputQty').val();
                    $('#inputPriceNoVat').val(inputPriceNoVat);
                } catch (e) {
                    $('#inputPriceNoVat').val(0);
                }
            }
</script>
NoWar
  • 36,338
  • 80
  • 323
  • 498