Javascript Validation after computation

I’m a novice when it comes to Javascript. I’ve tried searching the web for a way to add the numeric values of several fields and validate that they total 100% using Javascript. I’ve seen explanations for adding values. But how do I mimic the Input Validation using @Failure on a web based form. I need to somehow run Javascript that adds up all the values of the previous fields and create an alert if they don’t total 100 (all this before they move too far ahead on the form).

Subject: Javascript Validation after computation

If the fields you are using are text (which they shouldn’t, you’ll need to use parseFloat() or parseInt().

Here’s a quick sample which goes in the JSHeader:

function submitapproval(){

if(isvalid()){

//do whatever you want here

thisDoc.submit();

}

}

function isvalid(){

var thisDoc = document.forms[0];

//Managers is a drop-down list

if(thisDoc.Managers.options[thisDoc.ChoiceApprover.selectedIndex].text == “Choose one …”){

alert(“Please choose a valid project manager from the list.”)

thisDoc.Managers.focus();

return false;

}

//Approver is a regular text input (could be a number)

if(thisDoc.Approver.value == “”){

alert(“Please enter a valid approver.”)

thisDoc.Approver.focus();

return false;

}

else{

return true;

}

}

In my case I am simply validating them, but one of the if’s in the isvalid() function could do something like this:

(assuming docThis=document.forms[0])

var total = docThis.field1.value + docThis.field2.value;

if(total != 100){

alert(“The percentages must add up to 100%”)

return false;

}

else return true;

You could always make it easier to read if you used a loop to loop through the fields and add them, but I used a simple example to demonstrate.

Good luck.

Subject: RE: Javascript Validation after computation

Just a note here – it’s highly unlikely that the percentages will ever add up to 100% if you allow fractional values (JS’s floating point math is not its best feature), so you might want to check for bigger than 99 and less than 101.

Subject: Thanks for the input!