Search code examples
javascripthtmlforms

having trouble changing Js variable to user input value from <input>


There is a user input field in an HTML form. My intention is for the user's inputed value to become the value of the variable 'price'. I have been unable to figure out how to do this. Can someone please steer me in the right direction.

// Variables
const button = document.getElementById('button');
const returnChange = document.getElementById('return-change');
const returnStatus = document.getElementById('return-status');
const cid = [
  ['PENNY', 1.01],
  ['NICKEL', 2.05],
  ['DIME', 3.1],
  ['QUARTER', 4.25],
  ['ONE', 90],
  ['FIVE', 55],
  ['TEN', 20],
  ['TWENTY', 60],
  ['ONE HUNDRED', 100]
];

let cash = document.getElementById('payment');
let price = document.getElementById('price').value;


  console.log(price);
  console.log(cash);
  console.log(cid);
        <div id="price-div">
            <form>
                <label for="price" >Purchase Price:
                    <input id='price' name='price' type="number" required />
                </label>
            </form>
        </div>

        <div id="payment-div">
            <label for="payment"> Payment Amount:
                <input id='payment' type="number" required />
            </label>
        </div>
        <div id="button-div">
            <button id="button" type="button" >Return Change</button>
        </div>
        <div id="change">
            <p id="return-change"></p>
            <p id="return-status"></p>
        </div>


Solution

  • You might want to use an addEventListener:

    const priceInput = document.getElementById("price");
    const priceHandler = e => {
      price = e.target.value;
      console.log(price);
    };
    priceInput.addEventListener('input', priceHandler);
    <form>
      <label for="price">Purchase Price:
               <input id='price' name='price' type="number" required />
           </label>
    </form>