0

How can create html template of following?

I have 6 textboxes. Textboxes 1-5 is for input and 6 is for output. In textbox 6, i want average value of other 5 textboxes without pressing any button in order to send result to textbox 6. Input of 5 textboxes may be optional(textbox value may be blank or number).

1 Answers1

4

I guess this is what you are looking for...

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Average Calculation</title>
</head>

<body>
    <input class="my_val" type="number" size="5" name="input1">
    <input class="my_val" type="number" size="5" name="input2">
    <input class="my_val" type="number" size="5" name="input3">
    <input class="my_val" type="number" size="5" name="input4">
    <input class="my_val" type="number" size="5" name="input5">
    <input class="output" type="number" size="5" name="input6" readonly>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="app.js"></script>
</body>

</html>

app.js

$('.my_val').keyup(function () {
    var total = 0,
        count_field = 0,
        average;

    $('.my_val').each(function () {
        var val = parseInt($(this).val(), 10);
        if (!isNaN(val)) {
            count_field += 1;
            total += val;
        }
    });
    average = total / count_field;
    $('.output').val(average);
});

Here is the working fiddle JSFiddle

Hope I helped you.

laktherock
  • 427
  • 4
  • 19