user982124
user982124

Reputation: 4622

Javascript to validate hours per week/weeks per year entered

I have an HTML form that allows users to enter values for both "Number of hours per week" and "Number of weeks per year". We would like to include a check to ensure users don't enter values that exceed the possible maximum - this would check that "Number of hours per week" is not more than 168 and that "Number of weeks per year" is not more than 52.

I already have a script that calculates the "Average number of hours per week" based on the values entered into the previous 2 inputs as follows:

function calc(){

    $('#lastYear tr:has(.risk)').each(function(i,v){

        var $cel = $(v.cells);

        var $risk = $cel.eq(1).find('option:selected').val();
        var $numb = $cel.eq(2).find('input').val();
        var $weeks = $cel.eq(3).find('input').val();
        var $avg = ($numb * $weeks) / 52;
        var $avgRounded = Math.round( $avg * 10 ) / 10;

        $cel.eq(4).find('input').val($avgRounded);

    });   

I somehow need to extend this to also check the inputs are valid values and display a dialog with some text if they do enter an invalid value. I've setup a jsFiddle here to demonstrate the form. I'm learning Javascript as I go at the moment and are completely stumped on this one.

Update: I've added some code to check the number of hours but I'm now getting stuck in an endless loop where it displays the alert dialog box but I click OK and I get the same alert dialog box. See updated jsFiddle:

Upvotes: 0

Views: 315

Answers (1)

user2107469
user2107469

Reputation:

 var hour=document.getElementById('hour').value;
 var week=document.getElementById('week').value;

if(hour>168){alert ("error");return false;}
else if(week>52){alert ("error");return false;}
else{return true}

Upvotes: 1

Related Questions