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

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
keypress event has been deprecated. instead keydown can be used with some modifications. something like this if (!parseInt(event.key) && event.key != 'Backspace') {event.preventDefault();} developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event
0

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

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

5 Comments

How would I implement this javascript?
Never mind, that was a silly question. Placing in the bottom between the <script> tags works fine. Thanks!
How can I prevent the user from backspacing my initial value? This prevents letters and numbers only.
Just run it on your page, probably with <script>*javascript code*</script>
This should do. document.getElementById('rating').onfocus = function() { return this.blur(); }
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);
    


}

Comments

0

in React Material text field, this will work on others scenario

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



<TextField id="offerCode" name="offerCode" type="number" label="label" variant="outlined" onKeyDown={numericFilter}
                    onChange={handleChange} />

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.