Paul O'Brien Paul O'Brien - 9 months ago 51
jQuery Question

How to get appended output to refresh each time new input is entered?

I'm using jQuery to make an income calculator in which two HTML inputs in a form are added together and appended to a .div to give the total amount of income. It's successfully doing this, however as opposed to replacing the outputted total each time I enter a new number, it adds it onto the end of the previous total, e.g. £24£45.

How would I replace the output each time a new calculation is made?

On a side note, if I only enter a number into one of the input boxes I get an output of "NaN", is there any way to get rid of this and output simply the single number?

Thank you.



$(document).ready(function () {
$(".incomeform").blur(function () {
primaryincome = $("#primaryincome").val();
otherincome = $("#otherincome").val();
totalincome = parseFloat(primaryincome) + parseFloat(otherincome);
$(".incometotal").append("£" + totalincome)
})
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--income-->
<div class="main">
<div class="container">
<div class="incometotal">Income Total: </div>
<div class="row">
<form id="incomeform">
<div class="col-xs-6">
<input id="primaryincome" class="incomeform" type="text" placeholder="primary income">
</div>
<div class="col-xs-6">
<input id="otherincome" class="incomeform" type="text" placeholder="other income">
</div>
</form>
</div>
</div>
</div>




Answer

Use .html() not .append():

$(document).ready(function () {
    $(".incomeform").blur(function () {
        primaryincome = $("#primaryincome").val() || 0;
        otherincome = $("#otherincome").val() || 0;
        totalincome = parseFloat(primaryincome) + parseFloat(otherincome);
        $(".incometotal").html("£" + totalincome)
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--income-->
      <div class="main">
         <div class="container">
            <div class="incometotal">Income Total: </div>
            <div class="row">
                 <form id="incomeform">
                     <div class="col-xs-6">
                         <input id="primaryincome" class="incomeform" type="text" placeholder="primary income">
                     </div>
                    <div class="col-xs-6">
                         <input id="otherincome" class="incomeform" type="text" placeholder="other income">
                     </div>
                 </form>
             </div>
          </div>
      </div>

Note that I also added || 0 so that you don't get NaN when only one input has a value.