Search code examples
javascripthtmlformsrequired-field

Wanting Form requirement one cell to equal other cells prior to submit


I don't know JavaScript at all. I've used Jotform to create a web based form with a whole bunch of conditions attached to it because I don't have a clue how to do that. Changed a lot of it to php so I can access my db. Anyway. It's a employee time card form. We have a few fields where total time is required. The first field is total hours worked. Then goes onto job1, job2, job3, and job4. In job1 it says total hours on that job, job2 total hours, job 3 ect. I'm looking for a script that if job1,2,3,4 & 5 doesn't equal their original input of hours then display error.

Total Hours Worked = 8
Job1 Hours =3
Job2 Hours =5
JOb3 Hours =1
DISPLAY ERROR

Total Hours Worked = 8
Job1 Hours =1
Job2 Hours =4
Job3 Hours =2
Job4 Hours =1
ALLOW FORM TO SUBMIT

Is that something quite complicated.


Solution

  • I lazily hard coded the number of jobs, but this does what you want.

    <script type="text/javascript">
    function checkHours() {
    totalHours = Number(form.total.value);
    realTotal = 0;
    for (x = 1; x <= 4 /* hard-coded job count */; x++)
        realTotal += Number(eval("form.job" + x + ".value"));
    if (totalHours != realTotal) {
            alert("Total hours does not match cumulative job hours");
            return false;    
    }
    }
    </script>
    <form name="form" method="post" onsubmit="return checkHours()">
    <table>
    <tr>
        <td>Total Hours</td><td><input type="text" name="total"/></td>
    </tr>     
    <tr>
        <td>Job 1</td><td><input type="text" name="job1"/></td>
    </tr>   
    <tr>
        <td>Job 2</td><td><input type="text" name="job2"/></td>
    </tr> 
     <tr>
        <td>Job 3</td><td><input type="text" name="job3"/></td>
    </tr> 
    <tr>
        <td>Job 4</td><td><input type="text" name="job4"/></td>
    </tr>     
    </table>
    <input type="submit" value="Submit">
    </form>
    

    If this is in case of mistakes: my solution will suffice. If it's because of highly untrustworthy employees that would intentionally attempt to fake hours: Bubbles is right and you should check it with php as well.