Search code examples
javascriptinputbox

Get value from input box with js


I have no idea how to get value from input box. Right now when I click BET button it just subtracts 100, I want to achieve so when I enter the value in the text box and hit bet it'll subtract the value which I've entered from the balance. Here is my code:

HTML:

<div>
    <input type="text" value=0 name="betAmount">
    <button class="betBTN">BET</button>
</div>

JS:

document.addEventListener('DOMContentLoaded',function() {
document.querySelector('.betBTN').addEventListener('click', function() {
      var toAdd = document.querySelector('div').textContent - 100;
      document.querySelector('div').innerHTML = "";
      document.querySelector('div').insertAdjacentHTML('afterbegin', toAdd);
    });
});

Any suggestions?


Solution

  • Replace your 100 with

    document.querySelector("input").value;
    

    This line will get the value of input element

    document.addEventListener('DOMContentLoaded',function() {
    document.querySelector('.betBTN').addEventListener('click', function() {
          var toAdd = document.querySelector('div').textContent - document.querySelector("input").value;
          document.querySelector('div').innerHTML = "";
          document.querySelector('div').insertAdjacentHTML('afterbegin', toAdd);
        });
    });
    Balance: <div>1000</div>
        <input type="text" value=0 name="betAmount">
        <button class="betBTN">BET</button>