skip to Main Content

I want a text field where users can write only 1, X or 2 (like a bet). Only one of them, so limited to one character and only these three options. Also the X should be capitalized and not a small x.

Thanks in advance

Do not know what to try :/

3

Answers


  1. <input type="text" pattern="^(1|X|2)$" />

    Login or Signup to reply.
  2. That sounds like a job for radio/button/dropdown, but if you insist using an input, here’s a solution

    <input oninput="this.value = this.value.replace(/[^12X]/g, '')" maxlength="1" />

    As a bonus, here’s a more "user friendly" approach that automatically convers small x into X and replace the user input right away without requiring user to delete the previous one first.

    <input oninput="this.value = this.value.toUpperCase().replace(/.*([12X]).*|.*/g, '$1')" />
    Login or Signup to reply.

  3. About the Problem

    So you want text field with max-length of 1 and user can only input either 1 , X ,2.



    Approach

    • first create a input field and with attribute maxlength="1" will limit its length.

        <input type="text" maxlength="1" oninput="validate(this)">
      
    • Now we have to validate the input it must be from required values i.e either 1,X,or 2 so that thing will be handled by validate function.

      function validate(input) {
                const validchar = ['1', 'X', '2'];
                
                if (!validchar.includes(input.value)) {
                    input.value = '';
                }
            }
    
    
    • this function is used to check the userinput belongs to validchar array or not.
    • if value is not matched then this will make it empty.

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