Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...