Home > Blockchain >  Obtain value from an input in real time
Obtain value from an input in real time

Time:12-31

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 >
   <h3 >Buy</h3>
   <form action="/dashboard/" method="POST">
      <div >
         <input type="number" id="buyA" min="3" name="buyA" placeholder="Ammount">
         <div >
            <button >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 buyAmmount = document.getElementById('buyFormAmmount').value;
    if (!buyAmmount || <= 0) = "?";
    return buyAmmount;
</script>

CodePudding user response:

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>

CodePudding user response:

You need to create function that will be called when input of id buyForm changes. In that function, you need to get the value of input, calculate 'the second X', and set inner html for span HTML elements that should be in your button of class btn btn-success.

  • Related