user3011784 user3011784 - 1 month ago 13
HTML Question

how can I manipulate input value in JS to re-display in my HTML

I want to grab the input number value in HTML (everytime it's being changed by the user), do some math formula with the value, and re-output the data (without reloading) on the page.

my HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

QTY: <input type="number" name="qty" value="1" min="0" max="100" id="qty" ><br>
$<span id="total"></span>


my JS:

<script>
var qty = 1;
var total;
qty = setInterval(function() {ObserveInputValue($('#qty').val()); }, 300);

total = qty * 85;
$("#total").html(total);
</script>


and JS fiddle:
https://jsfiddle.net/bcxL3usw/

Not sure where my error is. I think I may have to put
$("#total").html(total);
in the setInterval function, but nothing seems to work.

Thanks

Answer

setInterval(function() { 
$("#total").text($('#qty').val()*85);
}, 300);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
QTY: <input type="number" name="qty"  value="1" min="0" max="100" id="qty" ><br>
$<span id="total"></span>

UPD:

setInterval(function() {
  let x = 0;
  if (parseInt($('#qty').val()) < 3) {
    x = $('#qty').val() * 85;
  } else {
    x = $('#qty').val() * 100;
  }
  $("#total").text(x);
}, 300);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
QTY:
<input type="number" name="qty" value="1" min="0" max="100" id="qty">
<br>$
<span id="total"></span>