I have a HTML5 input form, which needs to accept only the numbers 1, 2, or 3. This is not just allowing min/max for validation. The form field should not allow invalid characters to be entered.
So far I have this below, and it works, but with any number. Also, the input must not allow numbers such as 11, 12, 13, 21, 22, 23, 31, 32222, etc.
<input
type="number"
id="endLegDarts"
class="form-control"
min="1"
max="3"
maxlength="1"
aria-describedby="endDartsHelp"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
required="required"
/>
You could do it with a simple html5 input field with a pattern="[1-3]"
attribute:
input:invalid { border: red solid 3px; }
<input type="text" name="endLegDarts" pattern="[1-3]" />
OK, this one will only allow the single characters "1","2" or "3" to be entered:
<input type="number" name="endLegDarts" placeholder="please enter 1, 2 or 3" oninput="this.value=this.value.match(/[1-3]/)">
You should try using div instead of input like this: (type in this snippet to see)
var x = document.getElementById("my-input") window.onkeyup = function(e){ e = e || window.event; if(e.keyCode === 49){ //keycode for 1 x.innerHTML = "1" } else if(e.keyCode == 50){ //keycode for 2 x.innerHTML = "2" } else if(e.keyCode == 51){ //keycode for 3 x.innerHTML = "3" } }
<span>type here</span> <div id="my-input"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.