Don't allow typing numbers between max and min value

我的未来我决定 提交于 2019-12-07 16:03:45

问题


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


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/46325574/dont-allow-typing-numbers-between-max-and-min-value

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