1

For the numeric input element, is there a way to check if there is only a minus input? I can do this in a bad way in the example below. I'm looking for a more precise, simple method that I can access via the element.

When input is only - => numberInput.value equals to empty string also innerText and innerHTML equals to empty string.

var lastKey;
var checkNegativeSign = function() {
  let numberInput = document.querySelector("input");
  if(lastKey === '-') {
    document.getElementById("result").innerText = "is negative";
  } else {
     document.getElementById("result").innerText = "";
  }
}

var onKeyUp = function(event) {
  // Should check Escape, ctrl etc.
  lastKey =event.key;
}
<html>

<body>
  <input type="number" onkeyup="onKeyUp(event)" />
  <button onclick="checkNegativeSign()">Check Negative Sign</button>
  <div id="result"> </div>
</body>

</html>
Muhammet Can TONBUL
  • 3,217
  • 3
  • 25
  • 37
  • 1
    I think it's simply because "-" is not a valid number so you get an empty value... You should maybe make the type of your input "text", in that case you could get rid of the "onkeyup" event. – Arcord Mar 03 '21 at 10:35
  • @Arcord `-` This is not a valid number, I agree with you, but to enter a negative value we start with it. So I expect the number element to give this information. – Muhammet Can TONBUL Mar 03 '21 at 10:45
  • 1
    I understand the issue but unfortunately I don't think it's possible : https://stackoverflow.com/questions/18852244/how-to-get-the-raw-value-an-input-type-number-field – Arcord Mar 03 '21 at 10:53

1 Answers1

-2

You could do

    let sign = Math.sign(Number(document.querySelector("input").value))
    console.log(sign === 1? "positive": "negative")
Jy T
  • 86
  • 8