Y
Y
Yan Alexandrov2021-02-26 14:34:34
JavaScript
Yan Alexandrov, 2021-02-26 14:34:34

How to prevent "e" and "+-" characters from being entered in type="number"?

I include Alpine.js as in the dock:

<script src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.js" defer></script>

And, in general, this is enough for further work.
Here is an input field:
<input type="number" x-data="{}" @input="if( $event.data === 'e' ) { $el.value = $el.value.replace('\[e]\i', '') }">

I enter numbers, but then if I enter the character "e", the field is completely cleared. It's strange that before the condition is checked, the value of $el.value is empty only when this character is entered. And cleaning therefore actually, also is made.

How can I set a condition in pure JS so as not to skip the "e" character, as well as plus and minus? And to work without the cleaning bug.

I understand these are features of type="number"? Since without alpine, cleaning is performed on JS, here is an example: https://jsfiddle.net/kickerock/d2nLqcgh/2/

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Y
Yan Aleksandrov, 2021-02-26
@YanAlexandrov

Here is an option, but it does not provide for the paste situation via ctrl+v:

<input type="number" x-data="{}" @keydown="if( ['+','-','e'].includes( $event.key ) ) $event.preventDefault()">

V
vreitech, 2021-02-26
@fzfx

the problem with cleanup is this: what do you think is equal before being assigned to ?
$el.value = $el.value.replace('\[e]\i', '')
$el.value.replace('\[e]\i', '')$el.value

S
Stalker_RED, 2021-02-26
@Stalker_RED

If you check keypress or even keydown - you will not need to do any replacements and cleanups, but you can simply do preventDefault and "cancel" the button click itself.
But input still needs to be checked, because can paste via ctrl+v.
And in general, why don't you like 'E'?
123e3 is 123000 (three zeros at the end)
1e10 is 1000000000000 (10 zeros)
These are quite valid numbers and they are.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question