How to fix this calculate script which has "NaN" in cost box?

I have a calculate script for cost, but I have a little problem when I try to empty price box, there is "NaN" in cost box.

I do not know where is the problem. I have made following changes: digitsVal=isNaN(digitsVal)?0:digitsVal; became var digitsVal=isNaN(digitsVal)?0:digitsVal; and first this code is working, but second I try to empty in cost box, there is still "NaN" in cost box.

How to fix this calculate script ?. Are there solution about this script?

Example :

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>berkelilingkesemua.info</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>

<body>

<script>
$(document).ready(function() {
  var price=$('#price'),
      phone=$('#phone_number'),
      digits=$('#digits'),
      sum=$('#sum');
  function calculateSum() {
    var digitsVal=parseInt(phone.val().substr(-2));
    digitsVal=isNaN(digitsVal)?0:digitsVal;
    digits.val(digitsVal);
    sum.val(parseFloat(price.val())+digitsVal);
  };
  phone.on('keyup', calculateSum);
  price.on('keyup', calculateSum);
});
</script>
        
        <table width="300px" border="1">
    <tr>
        <td width="40px">1</td>
        <td>Price</td>
        <td><input class="txt" name="price" type="text" id="price"></td>
    </tr>
    <tr>
        <td>2</td>
        <td>Phone Number</td>
        <td><input name="phone_number" type="text" id="phone_number"></td>
    </tr>
    <tr>
        <td>3</td>
        <td>2 Digits</td>
        <td><input class="txt" name="digits" type="text" id="digits" readonly></td>
    </tr>
    <tr id="summation">
        <td>&nbsp;</td>
        <td align="right">Cost :</td>
        <td align="center"><input type="text" name="sum" id="sum" value="0"></span></td>
    </tr>
</table>

</body>
</html>

Answers


Replace:

sum.val(parseFloat(price.val())+digitsVal);

With:

isNaN(parseFloat(price.val())+digitsVal) ? sum.val(0) : sum.val(parseFloat(price.val())+digitsVal);

I think this should work for you


Need Your Help

Entity Framework Dynamic Query Expression being ignored

c# linq entity-framework

I have an operation that takes a serializable QueryModel and converts it to an Expression to be passed to Entity Framework. My query against the database looks like:

Autocomplete a textbox in c#

c# textbox autocomplete

I'm trying to autocomplete a textbox. I'm retrieving values from Access Database. Just one field from a data table. If anyone can help me.