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

Categories

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

javascript - I would like to add numerical limits to this block of code

document.querySelectorAll('input').forEach(input => {
  input.addEventListener("keydown", function(e) {
    var charValue = String.fromCharCode(e.keyCode);
    if (((!/^(d+)?([.]?d{0,1})?$/.test(this.value + e.key)) && (e.which != 8))) {
      e.preventDefault()
    }
  })
})

SetPoint :<input id="input" type="text" name="setPoint"   max="5" min="1" />

this block of code is a bit beyond my understanding but I'm guessing you use e.something and <= in the if statement to add a less than or equal to limit the number that the form will accept

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Everytime you type a letter in the keyboard, you got a specific e.keyCode or e.key. Try to debug the value of each variable to understand the code.

To put a limit simply do a check to prevent default behavior (prevent further typing)

var nextValue = this.value + e.key;
if (nextValue < 1 || nextValue > 5) {
    e.preventDefault()
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...