0

I'm trying to format the value of my input using html5

I want as minimum value 001 , and as maximum value 999. When I type 1, I need the value to be translate in 001. And 10 in 010.

I have to fix the number of digits to 3. That's the same effect that "%03d"

I have checked on internet to find a solution was probably a pattern for my input but after a lot of attempts, I'm still stuck.

I created an interface, and I want to define a specific format for my input of type Number. This format is a format to 3 digits. So if you type 1, the input has to correct the value and translate to 001... or it can keep the old value and forget the wrong one.

input(type="number" min="001" max="999" pattern="xxxx", style="width: 45px ; text-align:center").input-sm#inputDut2-int

I know, or I think at least, that i can solve this with a pattern.

RaiZer
  • 39
  • 9
  • possible duplicate of http://stackoverflow.com/questions/2686855/is-there-a-javascript-function-that-can-pad-a-string-to-get-to-a-determined-lengt – Regis Portalez May 17 '16 at 14:35
  • Thanks you. I already tried something like that. But when i use the arrows at the right of my input, to control the value of the input, if my actual value is 001 and that i click the +1 arrow, the next value is 2. Any value of less that 3 digits musn't exist for me. – RaiZer May 17 '16 at 14:41

1 Answers1

0

On a number input, you won't be able to enter "012", since 012 === 12. You have instead to use a text input.

On this text input, you can format the input as required, simply by padding the value:

function padLeftWithBounds(input, padChar, maxLength, min, max) {
  if (input <= min)
    return min;
  if (input >= max)
    return max;

  var s = input.toString(10);
  var padding = "";
  for (var i = 0; i < maxLength; ++i)
    padding += padChar;

  return padding.substring(0, maxLength - s.length) + s;
};

$("input").on("keyup", function() {
  if (!$(this).val())
    return;
  $(this).val(padLeftWithBounds(parseInt($(this).val()), '0', 3, 0, 999));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" />
</form>
Regis Portalez
  • 4,675
  • 1
  • 29
  • 41
  • My problem comes from the display of values in the input. i don't want to work on the string in the input but to force a format, so that the user can't type anything else that a number with 3 digits. Sorry if my question isn't clear – RaiZer May 17 '16 at 15:01
  • Okay after rekorking and re-reading your post i finally understood what you were explaining me. Your code works fine and i just have to transform the string in a number to solve my problem. Thank you ! – RaiZer May 18 '16 at 07:26