Search code examples
javascripthtmlonkeyup

On keyup is not satisfying the condition


<label> Telugu</label>         
    <input type="text" onkeyup="return isNumber(event)" name="telugu"  id="telugu" maxlength="3"/> <br> <br>


JS 

<!DOCTYPE html>
<html>
<head>
<script>
function isNumber(event){
    var k= event.keyCode;
    console.log(k);
    if((k>47 && k<58))   /// THIS IS NOT WORKING
{
        console.log("entered");
        var s1 = document.getElementById("telugu").value;
        var s2= document.getElementById("hindi").value;
        var s3= document.getElementById("english").value;
        var s4= document.getElementById("maths").value;
        var s5= document.getElementById("science").value;
        if(s1<0 || s1>100){
            console.log("tel")
            document.getElementById("telugu").value = 0;      
        }

I want to input only numbers in a textbox. the condition is not working. If the value in the textbox is less than 0 or greater than 100. then I am resetting the value to 0. Resetting is working but the characters are also entering.


Solution

  • You could use a regex to remove everything that is not a digit. I also change to the input event which fires whenever the input changes.

    If you want to force numbers you could also just set the type to type="number". The benefit for this is that it will automatically show the number keyboard on phones and tablets, though you can show this as well with the inputmode="numeric" attribute

    // Get the textbox
    const telugu = document.getElementById("telugu");
    
    // Add event that fires whenever the input changes
    telugu.addEventListener("input", () => {
        // Replace everything that is not a digit with nothing
      const stripped = telugu.value.replace(/[^\d]/g, "");
      
      // If the value is below 0 or above 100 set it to 0, else enter the stripped value
      stripped < 0 || stripped > 100
        ? telugu.value = 0
        : telugu.value = stripped;
    });
    <label for="telugu">Telugu</label>
    <input type="text" name="telugu" id="telugu" maxlength="3"/>

    Without comments:

    const telugu = document.getElementById("telugu");
    
    telugu.addEventListener("input", () => {
      const stripped = telugu.value.replace(/[^\d]/g, "");
      
      stripped < 0 || stripped > 100
        ? telugu.value = 0
        : telugu.value = stripped;
    });
    <label for="telugu">Telugu</label>
    <input type="text" name="telugu" id="telugu" maxlength="3"/>

    Simplified:

    function validateValue(event) {
      var input = event.target;
      var stripped = input.value.replace(/[^0-9]/g, ""); /* Everthing that is not (^) in the range of 0 through 9 */
      
      if(stripped < 0 || stripped > 100) {
        input.value = 0;
      } else {
        input.value = stripped;
      }
    }
    <label for="telugu">Telugu</label>
    <input type="text" oninput="validateValue(event)" name="telugu" id="telugu" maxlength="3"/>