HTML Form constrain by JavaScript--number issue -


i writing form ask input lower , upper limit of weight range , return objects within weight range. in order prevent user entering lower limit>upper limit(eg. lower limit=5 , upper limit=2), used javascript below. when testing, form generating expected result when both upper limit , lower limit less 10.
however, returns "lower limit greater upper limit" error message when try on lower=2/upper=10 or lower=9/upper=10
in addition, when try lower=2 , upper=30, works again. (i using chrome testing) seems comparing first digit of lower , upper input. not sure if caused incorrect input type or javascript. can resolve problem? thanks

html5 form:

<label>please enter lower limit: <input type="number" name="weightl"  step="0.00000000001" min="0" id="weightl" autofocus required    placeholder="accepts decimal places"/></label>  <label>please enter upper limit:<input type="number" name="weightu" step="0.00000000001" min="0" id="weightu" autofocus required  placeholder="accepts decimal places"/></label>  <input type="submit" value="submit"/> <input type="reset" value="reset"> 

javascript:

 <script type="text/javascript"> window.onload = function () { document.getelementbyid("weightl").onchange = validateweight; document.getelementbyid("weightu").onchange = validateweight; } function validateweight(){ var up=document.getelementbyid("weightu").value; var low=document.getelementbyid("weightl").value;  if(low>up) document.getelementbyid("weightu").setcustomvalidity("upper limit has equal or greater lower limit"); else document.getelementbyid("weightu").setcustomvalidity('');   } </script> 

you're comparing strings, not numbers.

if (+low > +up) 

would 1 way fix that.

the "value" property of form field string. javascript string comparison not automatically treat strings numbers because numbers. preceding variable reference + forces conversion numbers. there other ways of doing it:

if (number(low) > number(up)) 

or

if (parsefloat(low) > parsefloat(up)) 

etc.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -