skip to Main Content

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>

2

Answers


  1. We need a little more detail on what you are seeing happen when you try the above. However, looking at the code, some suggestions:

    1. You don’t need the ‘return getValue()’. getValue() alone is fine.
    2. You can get the value from the element returned
    function getValue() {
      let element = document.getElementById("price");
      let value = element.value;
      console.log(value)
    }
    <form onchange="getValue()">
      <label for="price">Purchase Price:
           <input id='price' name='price' type="number" required />
       </label>
    </form>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search