Don't allow typing numbers between max and min value

I'm working on an Angular 4 project. I have an HTML <input type="number"> with min max and step attributes. My goal is to prevent typing numbers beyond the min-max range that is user friendly. How can I do that?

function myFunction(e) {
    var min = -100;
    var max = 100;

    var txtValue = document.getElementById("txt").value;
    var pressedValue = e.key;

    var combined = parseFloat(txtValue, pressedValue);
    console.log(`OLD:${txtValue}\nNEW:${pressedValue}\nCOMBINED:${combined}`);
    if (combined > max) {

        e.preventDefault();
        console.log('ohhw snapp');
    }
}
<input type="number" id="txt" value="Hello" onkeydown="myFunction(event)" min="-100" max="100" step="0.05">

My JSFiddle example

Upvotes: 4

Views: 2798

Answers (2)

Tom Dugovic
Tom Dugovic

Reputation: 51

For UX reasons, I'd recommend something more like this. It may confuse the user if they just think their keyboard is not working.

$('.range-enforced').on('change', function(e){
  var min=parseFloat($(this).attr('min'));
  var max=parseFloat($(this).attr('max'));
  var curr=parseFloat($(this).val());
  if (curr > max) { $(this).val(max); var changed=true; }
  if (curr < min) { $(this).val(min); var changed=true; }
  if (changed) {
    $warning = $(this).siblings('.warning')
    $warning.text('Only ' + min + ' through ' + max + ' allowed');
    $warning.show()
    $warning.fadeOut(2500);
  }
});
input + .warning {
  background: #ffff99;
  display: inline-block
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="range-enforced" min="-100" max="100" />
<div class="warning" style="display: none;"></div>

Upvotes: 3

Andrew L
Andrew L

Reputation: 5486

The first problem I see is you are providing 2 parameters to parseFloat which only accepts 1 (maybe you got confused with parseInt which takes 2 parameters- a string and a radix. You should combine the numbers first and do 1 parse float on the combined value.

for example

function myFunction() {
  var min = -100;
  var max = 100;
  
  var inputRef = document.getElementById("txt");
  var txtValue = inputRef.value;
  if(isNaN(parseFloat(txtValue))){
    console.log("warning input is not a number");
    return;
  }
  var newNum = parseFloat(txtValue);
  console.log(`NEW:${newNum}`);
  if (newNum > max || newNum < min) {
    console.log('input not in range (' + min + ", " + max + ")");
    inputRef.value = "";
  }
}
<input type="number" id="txt"
        onkeyup="myFunction()"
        min="-100"
        max="100"
        step="0.05"
        >

The input will reset back to empty now if the input is not in range on keyup. As per the comment above you can use this to notify the user of the problem.

Upvotes: 0

Related Questions