Don't allow typing numbers between max and min value

╄→尐↘猪︶ㄣ 提交于 2019-12-05 23:47:47

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>

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!