RegEx only numbers and unit add problem with backspace

Viewed 119

How i can create a Input a field that accepts only numbers and always add unit at the end?

A solution for accepts only numbers using regex is:

HTML:

    <input name="distance">

Javascript (with jQuery):

     $('input[name="distance"]').on('input', function() {
        this.value = this.value.replace(/[^0-9]/g, '').replace(/^([\d]+)$/g, '$1 km');
    });

Works fine, but some problem occours when i tried to use backspace to correct the information.

2 Answers

Set the cursor at the end of the number value, in this case is -3 from the end of the input value due to the string " km".

Also check if the cursor exceeds the number value (if the cursor is within the appended string " km"), if so, move the cursor to the end of the number value.

$('input[name="distance"]').on('input', function() {
  this.value = this.value.replace(/[^0-9]/g, '').replace(/^([\d]+)$/g, '$1 km');

  var fieldInput = $(this);
  var fldLength = fieldInput.val().length;
  fieldInput.focus();

  var pos = fieldInput[0].selectionStart;
  // if cursor position is past the number value, reset the cursor to the end of the number value.
  if (pos > fldLength - 3) {
    fieldInput[0].setSelectionRange(fldLength - 3, fldLength - 3);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="distance">

Alternative without editing input

Possibly easier and more concise would be to display the units to the right of the input box (or in it) as I show in the snippet below.

This method is much simpler and often easier for a user to understand (better in terms of UI).

I also changed the regex from [^0-9] to \D (since they're identical, just \D is shorter).

$('input[name="distance"]').on('input', function() {
    this.value = this.value.replace(/\D/g, '');
});
*,input {
  font-family: Arial !important;
  font-size: 16px;
}
input {
  padding-right:1.5em;
  text-align:right;
}
input ~ span.unit {
  margin-left:-1.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name='distance'/><span class=unit>km</span>


Input type=number

Adding to the above logic, you can also use <input type=number /> and drop jQuery altogether as the following snippet suggests.

All current browsers support this input type: Mozilla input number documentation.

*,input {
  font-family: Arial !important;
  font-size: 16px;
}
input {
  padding-right:1.5em;
  text-align:right;
}
input ~ span.unit {
  margin-left:-1.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=number /><span class=unit>km</span>

Related