2

Given a text-field that accepts only one character for input, as follows:

<input type="text" maxlength="1" name="k1" placeholder="?" />

Is it possible to further restrict text input so that only a 1, X or 2 (like in a betting-system) validates?

slevy1
  • 3,797
  • 2
  • 27
  • 33
Daniel Jensen
  • 131
  • 1
  • 10

3 Answers3

7
<input type="text" max-length="1" name="k1" placeholder="?" pattern="[ABC]" />

will allow letters A, B and C. You can replace A,B and C with anything you want

Browser support: http://caniuse.com/#feat=input-pattern

Regex Guide: https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx

Uğur Gümüşhan
  • 2,455
  • 4
  • 34
  • 62
0

For allowing 1 2 and X , Here

pattern="[12X]" mean either 1, 2 or X

Note: Only <input type="text" max-length="1" name="k1" pattern="[12X]" />This will not work until unless you have a form and you submit. This will allow you put any character in input box. This will come in effect when user submit.

<form>
    <input type="text" max-length="1" name="k1" pattern="[12X]" />
    <input type="submit">
</form>
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
0

There are at least two ways to do this, one involves using the pattern attribute, a non-JavaScript solution, that certainly works; see solutions others provide below. But, if you need to really be more restrictive, here is a JavaScript solution that stops the user in their tracks from submitting invalid data.

HTML:

<form>
<label>Enter 1, 2, or x</label>
<input id="myinput" maxlength="1" type="text">
<input type="submit"><input type="reset">
</form>

JavaScript:

myinput.oninput = function() {
  if (myinput.value != 1 && myinput.value != 2 && myinput.value != 'x') {
    alert("Invalid: " + myinput.value);
  }
};

Full working example here

A good resource that explores the oninput and other events: https://javascript.info/events-change-input

slevy1
  • 3,797
  • 2
  • 27
  • 33