D
D
dimonfreeman2021-07-02 14:14:34
JavaScript
dimonfreeman, 2021-07-02 14:14:34

How to remove spaces and letters from input?

Please tell me how to remove all spaces and letters on the fly from input using pure js .

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2021-07-02
@dimonfreeman

input.addEventListener('input', event => {
    const element = event.target;
    const currentValue = element.value;
    const preparedValue = currentValue.replace(/\D/g, '');
    const start = element.selectionStart;
    const end = element.selectionEnd;
    
    if (preparedValue !== currentValue) {
        element.value = preparedValue;
        element.dispatchEvent(new Event('change', { bubbles: true }));
    
        if (event.inputType === 'insertText') {
            const offset = event.data.length;

            element.setSelectionRange(start - offset, end - offset);
        }
    }
});

For Vue https://codesandbox.io/s/qna-q1013532-zf2xk

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question