Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

javascript - Input - Limit number range

I have a text input which I want to limit to only numbers. No other characters. I also want to limit from 0 - 255.

If a an 'illegal' char, or amount is entered, I want it to wait a second then delete that character or number. I was so far able to get the illegal characters.

Here's what I want to do:

  • Make it wait a second, then delete it.
  • Limit number from 0 - 255.

If more than 255 gets entered, I just want the last digit to wait, then delete itself. Just like the 'illegal' chars.

I already got the illegal character implemented. Here's the code:

JSFiddle

$('input[name="number"]').keyup(function(e) {
  if (/D/g.test(this.value)) {
    // Filter non-digits from input value.
    this.value = this.value.replace(/D/g, '');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="number" />
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try using if condition to check if this.value is greater than 255 , if true , set this.value to first two characters of input using String.prototype.slice()

How about making it wait a second?

Try using setTimeout()

function disableInput(el) {
  // create array of checks on `el.value`
  var checks = [/D/g.test(el.value), el.value > 255];
  // if `el.value` contains non-digit character,
  // or is greater than 255 ;
  // `Array.prototype.some()` checks for `true` value
  // if either `checks[0]`, or `checks[1]` is `true` do stuff
  // else set `el.value` to user input
  if (checks.some(Boolean)) {
    // disable input
    $(el).prop("disabled", true)
    // delay 1 second
    setTimeout(function() {
      if (checks[0]) {
        // Filter non-digits from input value.
        el.value = el.value.replace(/D/g, '');
      }
      // if `this.value` greater than 255 , set `this.value` to 
      // first two characters of input
      if (checks[1]) {
        el.value = el.value.slice(0, 2);
      };
      $(el).prop("disabled", false).val(el.value).focus()
    }, 1000)
  }      

}


$('input[name="number"]').keyup(function(e) {
  disableInput(this)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="number" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...