I have a form with a question that has about 15 options. The user selects one or more options by entering a percentage in the box next to the option. Entering any percentage in a box means that option has been selected.
Here’s where (I think) I need some javascript: The total of the percentages a user enters across all options has to total 100%.
Would like to do this client-side with an alert, as opposed to server-side. The form is complicated and long. Ideally, the user should not be able to proceed to the next question unless the percentage totals 100. But I’d settle for validating it on clicking the submit button.
This depends a lot on how your form is set up but it should not be too difficult to set up a piece of JavaScript that does this. Something like:
function totalQuestion(q_prefix) {
var total = 0;
for (var i = 0; true; i++) {
var e = document.getElementById(q_prefix + i);
if (!e) break;
if (e.value) total += parseInt(e.value); // might want to parseFloat
}
return total;
}
In the above code the fields of each question are labeled with id’s that share some common prefix. You can call this function with that prefix to figure out what the total is. The only question is when do you want to check. You could check when the value changes in any of the input fields and only enable the submit button when all of the questions satisfy your requirements.
Of course, you need to check this property on the server as well in order to trust the authentication.