javascript validation for ordering of numbers -


the following code check validation numbers.num1,num2 , num3. validation works num1 less num2 less num3. order follow , working, after displaying alert message number entered , breaks order needs reset empty.

<form name="validateform" method="post">enter num1     <input type="text" id="num1" name="num1" value="" onchange="javascript:validate()" />     <br/>enter num2     <input type="text" id="num2" name="num2" value="" onchange="javascript:validate()" />     <br/>enter num3     <input type="text" id="num3" name="num3" value="" onchange="javascript:validate()" />     <br/> </form> 

code:

function validate() {     var num1 = document.validateform.num1.value;     var num2 = document.validateform.num2.value;     var num3 = document.validateform.num3.value;     var count = 0;     if (num1 != "") {         count++     }     if (num2 != "") {         count++     }     if (num3 != "") {         count++     }     var numarray = new array(count);     var flag = "false";     var j = 0;     if (!isnan(num1)) {         numarray[j] = num1;     } else {         flag = "true";     }       if (!isnan(num2)) {         if (flag == "true") {             alert("numbers not in order");             document.validateform.num2.value = "";             return false;         }         numarray[j] = num2;         j++;     } else {         flag = "true";     }     if (!isnan(num3)) {         if (flag == "true") {             alert("numbers not in order");             document.validateform.num3.value = "";             return false;         }         numarray[j] = num3;         j++;     }     if (numarray.length > 1) {         (var x = 0; x < numarray.length - 1; x++) {             if (numarray[x + 1] < numarray[x]) {                 alert("numbers not in order");                 return false;             }         }     } }   

i drop numbers array, , cycle through checking values values of next index. if make way through, have set. otherwise, it's bad set.

var numbers = [2, 3, 4],     inorder = checkvalues( numbers );  function checkvalues ( arr ) {     // cycle on every item in array, exclude last item     ( var = 0; < ( arr.length - 1 ); i++ ) {         // if current item greater item @ next index         if ( arr[ ] > arr[ + 1 ] ) {             // list not in order             return false;         }     }     // if made point, list in order     return true; } 

as resetting afterwards, can call .reset() method on form itself:

var myform = document.forms["validateform"];  /* ... */  if ( checkvalues( numbers ) ) {     myform.reset(); } 

Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -