0

I would like to remove all non-numeric characters from the user's input in an <input type="number"> element, but I cannot get this to work. I have code that works fine on an <input type="text"> element, but the exact same code is not working when you change text to number.

HTML:

<input type="text">
<input type="number">

jQuery:

// Works
$("[type='text']").on("change",function(){
    var x = $(this).val();
    x = parseInt(x.replace(/\D/g,''),10);
    if (isNaN(x)) {x = "";}
    $(this).val(x);
});

// Doesn't work
$("[type='number']").on("change",function(){
    var x = $(this).val();
    x = parseInt(x.replace(/\D/g,''),10);
    if (isNaN(x)) {x = "";}
    $(this).val(x);
});

Fiddle.

How do I get this to work?

Update: @axlpl's answer below got us to what we needed. I used his code as a starting point and modified it to make sure it worked with Apple's command key and also to allow certain other things to be done in the cell. Fiddle.

1
  • input type number does not give you the value when it is invalid. That is how it works, so it is not possible to remove the characters. Commented Nov 25, 2014 at 14:16

3 Answers 3

3

<input type="number"> has some kind of build in validation. The val() is empty as long as there are invalid characters in the field. So you can´t use your code to remove the non-numeric elements, because there will never be such an character in the value of the <input type="number">


Edit:

I recommend something like http://jqueryvalidation.org/. It will give you different validation options and has an easy to use error output. With this you could add some red text above the input and tell the user what he can and can´t enter in this field.

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

4 Comments

Is there any other way besides val() to access the data input by the user in an <input type="number">? You could conceivably swap out the number field with a text field on focus and then put the corrected value back in the number field, but that seems like a lot of hoops to jump through.
Well. What do you want to do with the input field? If you don´t want letters in it, than you have to do nothing, because there never will be a letter in it. There is an integrated error handler in it which makes the border red when you enter something not valid.
Rather than waiting for submission validation, we want to remove non-numeric characters on change or the like. So if a user enters "30k", it would be changed to "30" instead of sending back a null value.
If you want to do this use <input type="text">. I think the <input type="number"> will not work with your code. If you want to use it either way you should use the way @axlpl suggested.
2

here is your answer:

http://jsfiddle.net/qnb8ayr7/6/

JS with PASTE and CTRL + V

var ctrlDown = false;
var ctrlKey = 17, vKey = 86;

$("[type='number']").on("keydown", function(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode

    if (charCode == ctrlKey) ctrlDown = true;

    if(ctrlDown == true && charCode == vKey) {
        return true;
    }

    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;

}).keyup(function(evt)
{
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode == ctrlKey) ctrlDown = false;
});

$("[type='number']").bind("cut copy paste",function(evt) {
    var number = (evt.originalEvent || evt).clipboardData.getData('text/plain');
    x = parseInt(number.replace(/\D/g,''),10);
    console.log(number);
    $(this).val(x);
    evt.preventDefault();
});

5 Comments

And when they paste using a mouse?
@ShekharPankaj are you serious? So why use javascript if you can turn it off? lol, has you here about backend validation? I updated no paste ;)
Unfortunately we are going to need to let the users paste as it's fairly likely they'll be copying and pasting data from elsewhere. The keydown limitations are a good additional idea, but I can't restrict the pasting.
That fiddle's not working. The keydown capture is preventing command-v / ctrl-v. However, if you select paste from the pull-down menu, it does work. I've been trying to create an exception with e.metaKey that will let keyboard pasting pass through, but no luck yet.
Thanks, this got me to the answer I was looking for! I needed to accommodate Apple's command key as well, so I used metaKey instead of limiting it to just the ctrl key. I also wanted to allow certain other keys (arrows, etc.), so I made some other modifications. Fiddle. Follow-up question for you: I structured my code a bit differently than you did. Any benefit to doing it your way versus how I did it?
1

According to WHATWG,you shouldn't be able to get the value unless it's valid numeric input. The input number field's sanitization algorithm says the UA will set to empty string if the value is not proper floating point number.

IN short the algorithm say:

If the value of the element is not a valid floating-point number, then set it to the empty string instead.

By specifying <input type="number"> your browser is instructed to run the algorithm for you, thats why to allow non numeric you have to use <input type="text">

AND secondly you cannot use change event on this field . instead you have to use oninput to fire any event

FIDDLE to demostrate oninput

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.