Search code examples
jquerykeyup

input field value on keyup but also can be manual input


I have a total of 6 input fields like

<input type="text" name="count500" id="count500" value="">
<input type="text" name="count200" id="count200" value="">
<input type="text" name="count100" id="count100" value="">
<input type="text" name="count50" id="count50" value="">
<input type="text" name="count10" id="count10" value="">
<input type="text" name="total" id="total" value="">

On each of the first five's input field values, on keyup, the total is instanly shown on the "total" input field.

<script>
  function doTotal() {
    count500 = parseFloat($("#count500").val() * 500) || 0;
    count200 = parseFloat($("#count200").val() * 200) || 0;
    count100 = parseFloat($("#count100").val() * 100) || 0;
    count50 = parseFloat($("#count50").val() * 50) || 0;
    count10 = parseFloat($("#count10").val() * 10) || 0;
    total = count500 + count200 + count100 + count50 + count10;
    $("#totak").val(nc.toFixed(2));
  }

$('input').keyup(function() {
  doTotal();        
}); 
</script>

That is working well without an issue.

But I also like the ability for the user to manually type in a value in total. Currently anything that's typed into it disappears,

Any help is appreciated


Solution

  • Add a class inputValues to the input element other than the total. By adding the class you are excluding the input field for the toltal.

    HTML

    <input type="text" name="count500" class="inputValues" id="count500" value="">
    <input type="text" name="count200" class="inputValues" id="count200" value="">
    <input type="text" name="count100" class="inputValues" id="count100" value="">
    <input type="text" name="count50" class="inputValues" id="count50" value="">
    <input type="text" name="count10" class="inputValues" id="count10" value="">
    <input type="text" name="total" id="total" value="">
    

    jQuery

    function doTotal() {
      count500 = parseFloat($("#count500").val() * 500) || 0;
      count200 = parseFloat($("#count200").val() * 200) || 0;
      count100 = parseFloat($("#count100").val() * 100) || 0;
      count50 = parseFloat($("#count50").val() * 50) || 0;
      count10 = parseFloat($("#count10").val() * 10) || 0;
      total = count500 + count200 + count100 + count50 + count10;
      $("#totak").val(nc.toFixed(2));
    }
    $('input.inputValues').keyup(function() {
      doTotal();        
    });