Tuesday, January 9, 2018

HTML input type=number

HTML5 gives you a lot more input types. Well you may be required to support browsers that does NOT support it, well that's too bad.

Suppose you want a field that you want to only limit number, like a quantity field, phone number field or a credit card number CVV field, you can you input type="number".

https://www.w3schools.com/html/html_form_input_types.asp

Well this thing will give you annoying up/down arrow. Make sense for a quantity field, but not for a phone number field ok? Good news: CSS can hide it.

Since the dawn of HTML (I think) there is a maxlength field on the input type="text" but it won't work with "number"! so you can't put a maxlength=10!

Here you can play: https://www.w3schools.com/html/tryit.asp?filename=tryhtml_input_number Ah, there is "min" and "max" property for input type=number. BUT IT DOESN'T WORK. You can type more than 5 in Chrome, for instance. Firefox give you an error when you hover but you still can type. So I can't make it min=1 max=9999999999 if I want a 10 digit max.

Fortunately some CLEVER DUDES figured out how to do this.


<style>
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
input[type="number"] {
    -moz-appearance: textfield;
}
</style>

<input name="phonenumber"
oninput="maxLengthCheck(this)"
type = "number"
maxlength = "10"
min = "1"
max = "9999999999" />

<script>

  function maxLengthCheck(object)
  {
    if (object.value.length > object.maxLength)
      object.value = object.value.slice(0, object.maxLength)
  }
</script>
Well a number here is not whole number, but it can take decimal point too, it even takes more than 1 decimal point. and that decimal point is still annoying... there are people who use keypress event to limit 0..9 only but may not work on some phones.. oh there is the pattern attribute, but does not work! https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_pattern (it took more than 3 letters for me in Chrome)

No comments: