开发者

Javascript/Ajax/Jquery Dynamically calculate form on change

开发者 https://www.devze.com 2023-02-11 05:27 出处:网络
I have a small form which is going to be populated from Mysql and human input. What I want to do is populate 3 other fields based开发者_如何学JAVA on the other ones.

I have a small form which is going to be populated from Mysql and human input. What I want to do is populate 3 other fields based开发者_如何学JAVA on the other ones.

Example:

Total Parts (Mysql)

Labor (User)

Misc (User)

Sub Total (Dynamic total of above)

Tax (Dynamic calc of above - sub * 13%)

Total (Sub + Tax)

I have searched around but can not quite find what I am looking for, and my skills are zero in Javascript/Ajax/Jquery so I haven't been able to modify anything to work, although I have tried miserably.

Can someone help me out on this or point me to a script that may suit my needs.

Thanks


Alright sorry, I thought you were looking for some complex code. Here is a simple example of exactly what you're looking for.

<html>
<head>
</head>
<body>
<script>
function doMath() {
    var totalparts = parseInt(document.getElementById('parts_input').value);
    var labor = parseInt(document.getElementById('labor_input').value);
    var misc = parseInt(document.getElementById('misc_input').value);
    var subtotal = totalparts + labor + misc;
    var tax = subtotal * .13;
    var total = subtotal + tax;

    document.getElementById('subtotal_input').value = subtotal;
    document.getElementById('tax_input').value = tax;
    document.getElementById('total_input').value = total;
}
</script>

<div>Total Parts: <input type="text" id="parts_input" value="1" readonly="true" /></div>
<div>Labor: <input type="text" id="labor_input" onBlur="doMath();" /></div>
<div>Misc: <input type="text" id="misc_input" onBlur="doMath();" /></div>
<div>Sub Total: <input type="text" id="subtotal_input" readonly="true" /></div>
<div>Tax: <input type="text" id="tax_input" readonly="true" /></div>
<div>Total: <input type="text" id="total_input" readonly="true" /></div>
</body>
</html>

Obviously this doesn't grab the dynamic value from a database. If you use PHP you can swap this line:

<div>Total Parts: <input type="text" id="parts_input" value="1" readonly="true" /></div>

for one like this:

<div>Total Parts: <input type="text" id="parts_input" value="<?PHP include('getTotalParts.php'); ?>" readonly="true" /></div>

Where the getTotalParts.php is a file you make to get your database information. It can simply grab the information and do a "echo $totalParts;"


You can just use onblur (activated when a user leaves each of the input fields) to calcuate the fields.

...<input name="labour" id=total onblur="$('#total').val($('#sub').val() + $('#tax').va())">

You haven't provided enough information to comment on the "Total Parts" field.

0

精彩评论

暂无评论...
验证码 换一张
取 消