Search code examples
javascripthtmlkeyup

Javascript keyup function throwing wrong alert message


With the following script, i am trying to validate whether the refund amount wlt_ln_refund_amt is greater than the balance amount wlt_ln_bal using keyup function.

  • In my html read only field wlt_ln_bal (field type = number) i have a an amount 222.00
  • the other field wlt_ln_refund_amt (field type = number)

The testcase

  • for the value 3 the system is throwing an error message like "Refund amount Rs.3 is greater than Balance Rs.222.
  • for the values 1, 2 or 2000 the system is not throwing any errors

Here is my html code:

<form id="lnrefund" name="lnrefund" 
    method="post" role="form" 
    class="form-horizontal" 
    action="<?php echo $_SERVER['PHP_SELF']; ?>" 
    onsubmit="return (checkform() && confirm_update())">    
   <div class="form-group">
     <label class="col-md-2 col-xs-12 control-label">Loan Balance</label>
     <div class="col-md-3 col-xs-12">       
       <input id="wlt_ln_bal" Name="wlt_ln_bal" 
        type="number"value ="<?php echo $bal ?>" 
        class="form-control required" readonly/>
       <span class="help-block">Required</span>
     </div>
   </div>
   <label class="col-md-2 col-xs-12 control-label">Refund Amount</label>
   <div class="col-md-3 col-xs-12">
    <input id="wlt_ln_refund_amt" 
           Name="wlt_ln_refund_amt"type="number" step="0.01" 
           class="form-control" required/>
    <span class="help-block">Required</span>
   </div>
</form>

And this is the javascript

<script type="text/javascript">
$(function(){
    $("#wlt_ln_refund_amt").keyup(function () {
var ref = document.lnrefund.wlt_ln_refund_amt.value;
var bal = document.lnrefund.wlt_ln_bal.value;
if (ref>bal)
    { 
     alert('Refund amount Rs.'+ref+  '\nis greater than Available Balance Rs.'+bal)
          return true;
          }
      });
      });
</script>

Solution

  • It looks like the variables are being compared as strings (i.e. alphabetically) you should try something like

            var ref = parseInt(document.lnrefund.wlt_ln_refund_amt.value);
            var bal = parseInt(document.lnrefund.wlt_ln_bal.value);
    

    or maybe

            var ref = parseFloat(document.lnrefund.wlt_ln_refund_amt.value);
            var bal = parseFloat(document.lnrefund.wlt_ln_bal.value);
    

    if you're expectiong decimals