javascripthtmlbootstrap-5express-handlebarshbs

Obtain value from an input in real time


I am trying to get the value of an input in real time but I can't get it

I'm trying that in the bottom button the first X is the amount of carrots specified in the input above, and in the second X is a number that will be calculated in a script, all in real time (if the input number changes, the bottom ones will change automatically) but for that I need a way to get the value of the input in real time

Here's the code, I'm using express-handlebars and Bootstrap for the styles and classes

<div class="col-md-auto mx-auto">
   <h3 class="text-center">Buy</h3>
   <form action="/dashboard/" method="POST">
      <div class="form-group">
         <input type="number" id="buyA" min="3"class="form-control" name="buyA" placeholder="Amount">
         <div class="d-grid gap-2">
            <button class="btn btn-success">Buy X Things X</button>
         </div>
      </div>
      <input type="hidden" id="buy" name="buy" value="buy">
   </form>
</div>

One of the scripts I've tried is this one, but it doesn't show anything and I just put it in place of the X (I'm a bit of a newbie in HTML), that is, instead of the X I just put that Script to hopefully get its value

<script>
    let buyAmount = document.getElementById('buyFormAmount').value;
    if (!buyAmount || <= 0) = "?";
    return buyAmount;
</script>

Solution

  • You need to add an Event Listener on the input field, see exemple below.

    var x = document.getElementById('txt');
    x.addEventListener('input', function(){
        document.getElementById("myBtn").innerHTML="Buy "+x.value+" Rabbits by "+ x.value+" Carrots"
    });
    <input type="text" id="txt" name="txt" value="" >
    <button id="myBtn" value="myvalue" >Try it</button>