skip to Main Content

<input type="number" oninput="this.value=this.value.slice(0,5)"/>

I’m trying to limit the number of char allowed in the field, but when typing period, the cursor moves to the beginning and the period symbol is not typed?

How can I fix this behavior?

Thanks

Specified oninput field to slice the value of input field, it worked fine but when typing period symbol the cursors moves to the front, it doesn’t do that the second time.

enter image description here

2

Answers


  1. function limitsLength(inputElement, maxLength) {
                            let sanitizedValue = inputElement.value.replace(/D/g, '').slice(0, maxLength);
                            let cursorPos = inputElement.selectionStart + (sanitizedValue.length - inputElement.value.length);
    
                            inputElement.value = sanitizedValue;
                            inputElement.setSelectionRange(cursorPos, cursorPos);
                        }
    <input type="text" oninput="limitsLength(this, 5)" />
    Login or Signup to reply.
  2. The easiest solution that works is all browsers is to set the type to text. Then the maxlength will be honored and you will not need to modify the element. You can parse the value when you read it in your code.

    const elem = document.querySelector('input[name=usernumber]');
    
    // Only allow digits and a period
    elem.addEventListener('beforeinput', (event) => {
      const key = event.data;
      if (!((key === '.' && elem.value.indexOf('.') < 0) || (key >= '0' && key <= '9'))) event.preventDefault();
    });
    
    
    // parsing the value
    elem.addEventListener('input', (event) => {
      console.log('The value', parseFloat(elem.value))
    });
    input:invalid {
      background-color:red;
    }
     <input name="usernumber" type="text" inputmode="numeric" pattern="d*(.d*)?" maxlength="5" />

    inputmode="numeric" is a hint to the browser what keyboard to display.

    pattern="d*" tells the browser what input is valid. Note: You can still enter illagal characters, but then the field is invalid, and you can show that with some css.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search