Confused_Scruff Confused_Scruff - 6 months ago 46
SQL Question

Javascript/Ajax/Jquery Dynamically calculation form on change

I have a small form which is going to be populated from Mysql database and human input. What I want to do is calculate 2 other fields based on the other ones.

Example Form:


  • Indicator (MySQL) (a dropdown)

  • Hour Equivalent (MySQL)

  • SKS Equivalent (MySQL)

  • Amount (User)

  • Hour Total (Amount*Hour Equivalent)

  • SKS Total (Amount*SKS Equivalent)

  • Submit (Button to save into table)



This is an example for the calculation operation that I try to solve


  • Indicator = A

  • Hour Equivalent = 20

  • SKS Equivalent = 15

  • Amount = 2

  • Hour Total (Amount*Hour Equivalent) = 40

  • SKS Total (Amount*SKS Equivalent) = 30



I have searched around and try some of solutions but I can’t quite find what I am looking for, and my skills are not really good in Javascript/Ajax/Jquery so I haven't able to do anything to work, although I have tried miserably.

How to do it?

This is the HTML Form



<form>
<fieldset>
<legend>PSC Achievement</legend>
<!-- Button Drop Down -->
<div class="form-group">
<label for="buttondropdown">Indicator</label>
<button type="button" data-toggle="dropdown">
Choose
<span class="caret"></span>
</button>
<ul class="dropdown-menu pull-right">
</ul>
</div>

<label for="txtsks">SKS Equivalent</label>
<input id="txtsks" name="txtSks" type="text">

<label for="txtjam">Hour Equivalent </label>
<input id="txtjam" name="txtHour"type="text">

<label for="textjml">Amount</label>
<input id="textjml" name="txtAmount" type="text">

<label for="Totalhour">Hour Total</label>
<input id="Totalhour" name="Totalhour" type="text">

<label for="Totalsks">SKS Total</label>
<input id="Totalsks" name="Totalsks" type="text">

<label for="btn_submit"></label>
<button id="btn_submit" name="btn_submit">Submit</button>
</fieldset>
</form>




Answer

Your solution here : https://jsfiddle.net/tv94prmu/ . Calc function is a result of change event. Result will be displayed after one of fields will be filled

$(function(){
$('#txtsks,#txtjam,#textjml').change(function(){
calc();
})
function calc(){
    $('#Totalhour').val(parseInt($('#txtjam').val())*parseInt($('#textjml').val()))

  $('#Totalsks').val(parseInt($('#txtsks').val())*parseInt($('#textjml').val()))

}
})

Also, you need to include jquery library to page.