0

I have a situation where I'm trying to mask decimal length of varying lengths. One of the requirements is that the input needs to have a ',' between every 3 digits (inserted automatically). The precision of the decimals is fixed to what type they are (1 precision 2, precision, etc). So we could have inputs of the form

000,000.00

000,000.000

000,000

I've tried to create something like this in bootstrap as an alternative approach. However I can't seem to do it with input groups setting the input-group-addon width with normal bootstrap styling.

enter image description here

I was wondering if anyone has come across a good solution for this sort of input.

adc90
  • 303
  • 3
  • 10

1 Answers1

0

You could opt to use jQuery; for example, consider this script (it assumes an input with id number):

<script type="text/javascript">
  $(document).ready(function() {
    function reverseStr(str) {
      return str.split("").reverse().join("");
    }

    $('#number').on('change', function() {
      var value = reverseStr($(this).val().replace(/,/g, "")).match(/.{1,3}/g).join();

      $(this).val(reverseStr(value));
    });
  });
</script>

This script will apply a comma every three characters every time the input numberchanges (i.e. when input loses focus).

Check the snippet:

$(document).ready(function() {
  function reverseStr(str) {
    return str.split("").reverse().join("");
  }

  $('#number').on('change', function() {
    var value = reverseStr($(this).val().replace(/,/g, "")).match(/.{1,3}/g).join();

    $(this).val(reverseStr(value));
  });
});
.number, .decimals {
  margin: 0px;
  border: 0px;
  font-size: 12px;
  color: #777;
  padding: 8px;
  color: #999;
  font-weight: 500;
}

.number {
  width: 150px;
}

.decimals {
  width: 50px;
}

.inputs {
  background-color: #ccc;
  border: 1px solid #ccc;
  padding: 0px;
  display: inline-block;
}

.dot {
  width: 20px;
  display: inline-block;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="inputs">
  <input type="text" id="number" class="number" placeholder="000,000">
  <div class="dot">.</div>
  <input type="text" id="decimals" class="decimals" placeholder="00">
</div>
Gerry
  • 10,337
  • 3
  • 31
  • 40