Home > Enterprise >  I would like to turn this block of code into a keydown function that i could call from a html form
I would like to turn this block of code into a keydown function that i could call from a html form

Time:10-10

  SetPoint :<input id="input" type="text" name="setPoint" onkeydown="return keyispressed(event);"    max="5" min="1" /><br /> 



 SetPoint :<input id="input" type="text" name="setPoint" onkeydown="return keyispressed(event);"    max="5" min="1" /><br /> 
    
    
    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()
      }
    })

I want the setpoint html input form to call a keydown fucntion and then run the following code thanks for any help provided

CodePudding user response:

Few things:

  • Your HTML is invalid, You have duplicate ids which should be unique.

  • You should be selecting all inputs, looping through the list, and adding the event listener to each one

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 type="text" name="setPoint" max="5" min="1" /><br /> SetPoint :<input type="text" name="setPoint" max="5" min="1" /><br />

  • Related