I have a table and I want to allow submitting the form if and only if the total of each row must be =100 not less nor more and the total of each column must be <=100 and not more than 100
This is the old scenario each row and each column must be = 100.
Demo CODE:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
disableSave();
$(".sum").on("input", function() {
sumThisClass("1");
sumThisClass("2");
sumThisClass("3");
sumThisClass("4");
sumThisClass("5");
sumThisClass("6");
sumThisClass("7");
validateForm();
});
function validateForm() {
var hasError = $(".error").length > 0;
if (hasError) {
disableSave();
return;
}
var expectedTotal = $(".total").length * 100;
console.log(expectedTotal, getCurrentTotal());
if (expectedTotal == getCurrentTotal()) {
enableSave();
}
else {
disableSave();
}
}
function getCurrentTotal() {
var sumTotal = 0;
$(".total").each(function (index, el) {
var elValue = parseInt($(el).text());
if (!isNaN(elValue)) {
sumTotal += parseInt($(el).text());
}
});
return sumTotal;
}
function disableSave() {
$("#btn-save").prop("disabled", true);
}
function enableSave() {
$("#btn-save").prop("disabled", false);
}
function sumThisClass(className) {
var sumTotal = 0;
$("." + className).each(function(index, el) {
var elValue = parseInt($(el).val());
if (!isNaN(elValue)) {
sumTotal += parseInt($(el).val());
}
});
$(".sum-" + className).text(sumTotal);
if (sumTotal > 100) {
$(".sum-" + className).append("<div class='error'>cannot be greater than 100</div>");
}
}
});
</script>
<form action="test.php" method="post">
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>Total</td>
</tr>
<tr>
<td></td>
<td>
<input type="number" class="sum 1 5" min="0" max="100">
</td>
<td>
<input type="number" class="sum 1 6" min="0" max="100">
</td>
<td>
<input type="number" class="sum 1 7" min="0" max="100">
</td>
<td class="total sum-1"></td>
</tr>
<tr>
<td></td>
<td>
<input type="number" class="sum 2 5" min="0" max="100">
</td>
<td>
<input type="number" class="sum 2 6" min="0" max="100">
</td>
<td>
<input type="number" class="sum 2 7" min="0" max="100">
</td>
<td class="total sum-2"></td>
</tr>
<tr>
<td>TOTAL</td>
<td class="total sum-5"></td>
<td class="total sum-6"></td>
<td class="total sum-7"></td>
</tr>
</table>
<input type="submit" name="save" value="SAVE" id="btn-save"/>
I tried to change it but I couldn't succeed.
This is a rough idea:
you will change the old condition by this:
In this demo HTMLFormControlsCollection was used because it makes dealing with form controls easier with it's terse compact syntax. Added
<output>
tags to each total cells. All<input>
s and<output>
s have an id that's associated with it's cell (<td>
).Details are commented in Demo
Demo
Hope it's gonna work for you
my code looks dirty, but i just want you to know what exactly i did in each line.
btw, you can try this