I have a form with X amount of columns that are labeled C1, C2, C3..to CX. I also have a column labeled "Average" and another labeled "Target". The "Average" column finds the average of each row in columns C1 - CX. Is it possible for the "Average" column to dynamically change while user is filling in the form? If so, how?
If that is not possible, then how do I have the "Average" column update its value upon submitting the form with the edited C1-CX values?
Just looking for tips on how to deal with the Averages. I already have working C1-CX columns with pre-defined fields that save to a MYSQL database.
Add an event handler that triggers when any of the CX form field values have been changed (eg a user changing the value in it) and then re-calculate the average and display it in the average column.
Probably something like the following, assuming your CX forms are inputs:
document.getElementById("C1").addEventListener("input", function(){
// Any time the user changes a value in form 'C1',
// this function will be called so you can re-calculate
// a new average and stuff...
});
give all of them a specific class (eg "cx") and then with JavaScript and jQuery: http://jsfiddle.net/yw3Hy/4/
$(document).ready(function() {
$(".cx").change(function() {
var count = 0;
var sum = 0;
$(".cx").each(function() {
count++
sum = parseFloat(sum) + parseFloat($(this).val());
});
var avg = sum/count;
alert(avg);
});
});
Use mysql trigger to update your Average
field automatically when your records updated.
Run this trigger on your database (eg for 3 CX
field):
DELIMITER $$
CREATE TRIGGER `trigger_name` BEFORE UPDATE ON `table_name`
FOR EACH ROW BEGIN
SET NEW.Average = (NEW.C1 + NEW.C2 + NEW.C3) / 3;
END;
$$
DELIMITER ;
Also here is an introduction to mysql triggers maybe useful: http://net.tutsplus.com/tutorials/databases/introduction-to-mysql-triggers/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.