skip to Main Content

I am making a simple tip calculator and first of all I am trying to save the value of the bill amount which the user can type into the input field (this input field has a type number attribute). There aren’t any button to submit the value so I’d like to use the submit event for the addeventlistener instead of the click event. Inside the addeventlistener I am preventing the default behavior of the event and then I am trying the save the amount as a variable but the console is empty all the time.

Here is the HTML code:

<div class="form_bill">
    <h2>Bill</h2>
    <div class="input_icons">
      <i class="fa fa-usd icon"></i>
      <input type="number" class="form_input bill_input" placeholder="0"/>
    </div>
</div>

Here is my JS code:

const billInput = document.querySelector('.bill_input');

billInput.addEventListener('submit', function (e) {
    e.preventDefault();

    const billAmount = billInput.value;

    console.log(billAmount);
});

I tried to change the input tag to form tag, I tried to change the type number to type text, I tried the click event, no success. I’d like to save the input value as a variable so after that I could work with that value.

2

Answers


  1. The Submit event is triggered by <form> element not <input> element, you can listen for change event so anytime the value of input changes your event is triggered and you can save the most recent value

    billInput.addEventListener('change', () => {
        const billAmount = billInput.value;
        console.log(billAmount);
    });
    
    Login or Signup to reply.
  2. There are different event that are fired when the value of an input changes. The input event will fire when the value has changed. Read more about the input event.

    In general be careful not to have too many variables. In this case you would like to have billAmount as a variable for the value of the input — but the input already have that value, so why another variable — it is more code to keep track of? In this example you can always refer to the value by document.forms.bill.numberinput.value and just e.target.value inside the event callback function.

    document.forms.bill.numberinput.addEventListener('input', function(e) {
      const billAmount = e.target.value;
    
      console.log(billAmount);
    });
    <form name="bill">
      <h2>Bill</h2>
      <div class="input_icons">
        <i class="fa fa-usd icon"></i>
        <input type="number" name="numberinput" class="form_input bill_input" placeholder="0" />
      </div>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search