2

I have a number input text box and I want to allow the user to edit but do not want to allow the user to enter any other text except numbers. I want them only to be able to use the arrows on the number input box.

 <input type = "number" min="0" max="10" step="0.5"  input id="rating"   name = "rating" class = "login-input" placeholder = "Rating 1-5:" value="0">
Rohit416
  • 3,416
  • 3
  • 24
  • 41
user3474775
  • 199
  • 1
  • 2
  • 12

3 Answers3

9

You can achieve this by pure JavaScript. Create this function that you can reuse in your script.

function allowNumbersOnly(e) {
    var code = (e.which) ? e.which : e.keyCode;
    if (code > 31 && (code < 48 || code > 57)) {
        e.preventDefault();
    }
}

You may preferably call this onkeypress event handler.

<input type="text" id="onlyNumbers" onkeypress="allowNumbersOnly(event)" />

function allowNumbersOnly(e) {
    var code = (e.which) ? e.which : e.keyCode;
    if (code > 31 && (code < 48 || code > 57)) {
        e.preventDefault();
    }
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
    Try editing in me:
    <input type="text" id="onlyNumbers" onkeypress="allowNumbersOnly(event)" />
</body>
</html>

However, I would recommend the unobtrusive style of writing JS using because it is good to keep the HTML semantic and away from pollution. You can execute the function on event handler that we would attach to this text box using vanilla JavaScript or jQuery.

function allowNumbersOnly(e) {
    var code = (e.which) ? e.which : e.keyCode;
    if (code > 31 && (code < 48 || code > 57)) {
        e.preventDefault();
    }
}

// using classic addEventListener method:
document.getElementById('onlyNumbers').addEventListener('keypress', function(e){    allowNumbersOnly(e);
}, false);

//using jQuery
$(function(){
    $('#onlyNumbers2').keypress(function(e) {
       allowNumbersOnly(e); 
    });
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
    <div>
      Using addEventListener: <input type="text" id="onlyNumbers" />
    </div>
    
    <div>
      Using jQuery: <input type="text" id="onlyNumbers2" />
    </div>
</body>
</html>

To restrict every character you can just simply use e.preventDefault().

Besides, you can also use return false instead but preventDefault() is better in this case and return false should be chosen wisely. It is good to know the difference between both of them.

Rohit416
  • 3,416
  • 3
  • 24
  • 41
  • I would have thought jquery has a library by this time, but they are so screwy, due to various possible types of objects that can be passed. This worked for me beautifully – AlpharettaTechy Feb 11 '22 at 13:05
0

document.getElementById('rating').onkeypress = function() { return false; }

This will prevent the default behavior of keypresses on that element i.e. text showing up.

wavemode
  • 2,076
  • 1
  • 19
  • 24
0

HTML

 <input type="text"  class="IntOnly">

Javascript

let ele = document.getElementsByClassName('IntOnly');

for (const e of ele) {
    //e.addEventListener('change', filterNonIntOut.bind(null, e));
    //e.addEventListener('paste', filterNonIntOut.bind(null, e));
    e.addEventListener('input', filterNonIntOut.bind(null, e));


}

function filterNonIntOut(theTextbox) {
    //console.log(ele);

    let startPos = theTextbox.selectionStart;
    let endPos = theTextbox.selectionEnd;

    let str = theTextbox.value;

    str = str.trim();
    if (str == '') {
        theTextbox.value = '';
        return;
    }

    let result = "";

    for (var i = 0; i < str.length; i++) {

        let ch = str.charAt(i);
        //console.log(ch);
        if (ch === '1'
            || ch === '2'
            || ch === '3'
            || ch === '4'
            || ch === '5'
            || ch === '6'
            || ch === '7'
            || ch === '8'
            || ch === '9'
            || ch === '0'
        ) {
            result += ch;
            
        }
        else {
            startPos -= 1;
            endPos -= 1;
        }
    }
    theTextbox.value = result;
    theTextbox.focus();

    theTextbox.setSelectionRange(startPos, endPos);
    


}
EKanadily
  • 3,831
  • 3
  • 35
  • 33