I want to perform a calculation on the difference between the number the user has entered in a text input for each answer in a question, and the total marks for the question.
I have a jsfiddle application which currently do this. When you change a value with in an answer's text input, it will calculate the difference between that number entered and the total marks which belongs to that question.
My problem is that at the moment it only works if I have either one or 2 answers. But a question can have numerous answers, they can have 3, 4, 5 even 10 answers and more. So my question is that how can the fiddle below can be changed so that it can perform calculations for multiple textboxes, not just 2 text boxes?
http://jsfiddle.net/jTXy5/3/ This jsfiddle has a question which contains 3 answers. But the third text input doesn't get calculated
Below is the example of what should happen:
Question No. Question Answer Marks per Answer Total Marks
1 Here are 2 answers B (text input) = 2 1
D (text input) = 1
E (text input) = 1
2 Here is a single answer True (text input) = 5 0
As you can see in the table above, the text inputs for the answers in question 1 equals 4 altogether. So 5 (from total marks for question 1) minus 4 = 1 (Total marks now equals 1)
For question 2, the text input for the answer in question 2 equals 5, so 5 (from total marks for question 2) minus 5 = 0 (Total marks now equals 0).
Below is the code which performs the calculation:
$('tr').each(function() {
var $input = $(this).find('input');
var $row = $(this);
var is_multiple = !$input.prop('readonly');
var rowClass = is_multiple ? 'multiple' : 'single';
if (is_multiple) {
var is_first = $row.find('td').length == 5;
rowClass += is_first ? ' first' : ' second';
} else {
/* readonly just needs marks changed once on page load */
$row.find('.noofmarkstd').text(5 - $input.val());
}
$input.addClass(rowClass);
});
$('input.multiple').keyup(function() {
var $input = $(this);
var is_first = $input.is('.first');
var $row = $input.closest('tr');
var $otherRow = $row[is_first ? 'next' : 'prev']();
var $marks = is_first ? $row.find('.noofmarkstd') : $otherRow.find('.noofmarkstd');
var calcs = 5 - ($input.val() || 0) - ( $otherRow.find('input.multiple').val() || 0);
$marks.text(calcs);
});
/* if need calcs for multiples generated on pageload trigger a change on the first in set*/
$('input.first').change();