Catch Value of input number

Asked

Viewed 707 times

1

I have a input of the kind number, and I would like it to accept only whole numbers.

Hence I am creating a function that limits the number of characters and replaces the digit that is not number with replace.

The problem, that this type of input accepts some characters like: "e+.,-". But when I try to get the value, it comes empty when typed something other than a number. So I can’t replace the characters.

$("[type=number]").val();

Regardless of whether there are other ways to do this by locking key, using input text etc. My question is:

Is there any way to get the value typed in the field INPUT NUMBER, instead of this blank value when typed characters other than numbers?

  • Precisely because of this, html itself filters the value. When you send the data it sends the data with special character?

  • @Glenysmitchell When I trigger the keyup event, it returns an empty variable " " ... Any character other than number returns empty. Hence it is not possible to replace. A few days ago I read something about default value... but I do not remember the difference, and if I doubt.

  • Already tried to rescue (same empty) and rewrite the field?

  • Do you speak store in a variable the previous value? and if it comes empty, I return with the previous value?

  • This, so if he enters a special character when he returns the empty value will erase the character.

2 answers

1


This is a limitation of the input itself. If you enter a value that can be considered ex.: 123e12 the $("[type=number]").val(); will return the correct value. If a "nonsense" number is typed ex.: 123e123456 the browser will ignore this value as it cannot be converted to Number. Here are some examples:

console.log( Number('123') ) //numero valido
console.log( Number('123e12') ) //numero valido
console.log( Number('123e12345') ) //numero invalido

The same goes for if you try to declare the input with these numbers:

<input type='number' value='123'/> <br />
<input type='number' value='123e12'/> <br />
<input type='number' value='123e12345'/>

thus typing an invalid number will not be possible to read the field value

  • Cannot take the input value, as it always returns empty. Just type "e+. ,-" it returns empty. The best option to heal, was to release only the number keys, hence never returns empty in the keypress...

0

If you want to clear the special characters, knowing that by default js will not accept the same in this type of field, take advantage of the keydown event you have already done to return the clean value.

In this example I did with Blur (when leaving the field):

$("#numeros").blur(function(){
    const valor = $("#numeros").val();
    $("#numeros").val(valor);
});

I believe there are other ways to do it, maybe even with masks and pregs. But this should help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.