-2

The code below prevents negative numbers in input for numbers but does not allow me to enter decimals if I clear input and try to enter let's say 0.41

<input class='input2' oninput="this.value = 
 !!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null" type='number' step='0.1' id='success' />

Update The code below allows decimals and prevents negative numbers but it does not allow me to place any condition. I also want to have one more condition of value can't be greater than 1: max = "1" not working

<input class='input2' min="0" max = "1" onkeypress="return event.charCode != 45" type='number' step='0.1' id='success'/>
Ujjawal Bhandari
  • 1,333
  • 1
  • 8
  • 16

1 Answers1

-1

var input = document.getElementById("success");


input.addEventListener("keyup", function(event) {
  // Number 13 is the "Enter" key on the keyboard
  if (event.keyCode === 13) {
    // Cancel the default action, if needed
    event.preventDefault();
    if (input.value < 0)input.value = -input.value
    if(input.value > 1)input.value = 1
  }
});
<input class='input2' min=0 max=1 type='number' step='0.1' id='success' />
DCR
  • 14,737
  • 12
  • 52
  • 115