2

I have the following code:

document.getElementById("decimal").addEventListener("click", () => {
  if (!inputBox.value.includes(".")) {
    inputBox.value += ".";
  }
});
<body>
  <div class="calculator">
    <input type="number" id="inputBox" placeholder="0">
    <div>
      <button class="decimal" id="decimal">.</button>
    </div>
  </div>
  <script src="script.js"></script>
</body>

When I add an EventListener to the button, a decimal should appear as the last character in the input field. However, because it is set to type="number", the function resets the input field entirely.

How can I add a decimal without resetting the value of the input field?

I have already tried changing the type of the input field to "text", but then the user can type alphabetical values into the input field, which I do not want.

Barmar
  • 741,623
  • 53
  • 500
  • 612
stilts15
  • 21
  • 1
  • 3
    Unless the input has a fractional step, it can only contain integers, and can't have a decimal point. – Barmar Jul 31 '23 at 22:52

1 Answers1

0

Add a step attribute to the input step=0.001 and then use value += '.0' to make it a decimal. The default number type is integer only.

document.getElementById("decimal").addEventListener("click", () => {
  if (!inputBox.value.includes(".")) {
  inputBox.setAttribute( "step", "0.001")
    inputBox.value += ".0";
  }
});
<body>
  <div class="calculator">
    <input type="number" id="inputBox" placeholder="0">
    <div>
      <button class="decimal" id="decimal">.</button>
    </div>
  </div>
  <script src="script.js"></script>
</body>
Martlark
  • 14,208
  • 13
  • 83
  • 99
  • Thanks @Martlark. If the inputBox value is 7, clicking the decimal button will turn it into 7.0. If the user then clicks another number (let's say 1) it will append it to the value, so it will become e.g. 7.01. I am looking for a way to just have 7. such that when the user clicks 1, it will become 7.1. Is this possible with an HTML input or should I use something else? – stilts15 Jul 31 '23 at 23:07
  • @stilts15 I've added the addAttribute call in the button click to make it a decimal . – Martlark Jul 31 '23 at 23:51
  • 1
    Sounds like you are getting into a complex behavior number component which would require plenty of code or React/VUE. – Martlark Jul 31 '23 at 23:55
  • Thanks for your help @Martlark - much appreciated! I will resort to using something other than an input field. – stilts15 Aug 01 '23 at 15:54