简体   繁体   中英

Remove “NaN” keyword from undefined object output

Please check code bellow. On modal opening output value displays something like "NaN" until i provide input. But i want to display just Blank field on output until i provide any input. How can i achieve that? Is it possible? happy coding to all. Please add bootstrap and jquery to test the code. thanks.

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
</head>
<body>

<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        <input type="text" name="" id="AmazonPrice" disabled="disabled" value="10"><br/>
        <input type="text" name="" id="BreakEven" disabled="disabled" value="20"><br/>
        <input type="text" name="" id="ComPrice" disabled="disabled" value="15"><br/>
        Input:<input type="text" name="" id="YourPrice" value=""><br/>
        Output:<input type="text" name="" id="YourProfit" value=""><br/>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>


<script type="text/javascript">

    $('#YourPrice').keyup(updatetxt);
    $('#AmazonPrice').keyup(updatetxt);

    function updatetxt() {
        var YourPrice = $('#YourPrice').val();
        var AmazonPrice = $('#AmazonPrice').val();
        var BreakEven = $('#BreakEven').val();

        var float_YourPrice = parseFloat(YourPrice);
        var float_AmazonPrice = parseFloat(AmazonPrice);
        var float_BreakEven = parseFloat(BreakEven);

        $('#YourProfit').val(profitCalculation(float_AmazonPrice, float_BreakEven, float_YourPrice));
    }
    updatetxt();

    function profitCalculation(AmazonPrice, BreakEven, YourPrice) {
        var YourProfit = YourPrice - (YourPrice / 100 * BreakEven + 0.30) - AmazonPrice;
        return YourProfit.toFixed(2);
    }

</script>
</body>
</html>

Quick solution: insert a conditional check if it's a NaN and return an empty string if so.

// inside function profitCalculation
return isNaN(YourProfit) ? '' : YourProfit.toFixed(2);

isNaN - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM