jQuery number format for HTML input number with dynamic decimals



I’ve seen a lot of similar threads or library but I haven’t found one I need.

I have preexisting code with many input[type=number] in the forms. I need to format the number value to local format when form is viewed at first load or when cursor/pointer is out of focus (onblur), and unformat the number to raw input when onfocus or when the form is submitted. The format are dot as separator and comma as decimal. The decimal numbers are dynamic, some don’t have decimals, some have 2 or 4, or in other words, the decimal format is only shown when the number has decimal. And when a field doesn’t have any value, still displays an empty string (“”) not zero (0). A field that has 0 value still displays a 0.

Example:

//Number is 1400.45
//Document ready: 1.400,45
//Onfocus: 1400.45
//Onblur: 1.400,45
//Onsubmit value send by PHP page load: 1400.45

Is there any way to do this or jQuery/javascript library for this?

Answer

I don’t think there is a library for such a specialized solution you are looking for but you can do it on your own. That’s the idea:

String.prototype.replaceLast = function(find, replace) {
  var index = this.lastIndexOf(find);
  if (index >= 0) {
      return this.substring(0, index) + replace + this.substring(index + find.length);
  }
  return this.toString();
};

let transformValue = function(value) {
  value = parseFloat(value);
  value = parseInt(value).toLocaleString() + '.' + parseInt(value.toString().split('.')[1] || '0');
  value = value.replace(',', '.');
  value = value.replaceLast('.', ',');
  return value;
};

let form = document.querySelector('#myForm');

window.addEventListener('load', function() {
  let inputs = form.querySelectorAll('input[type="text"]');
  for (let i = 0; i < inputs.length; i++) {
    let input = inputs[i];
    input.value = transformValue(input.value);
    
    input.onfocus = function() {
      this.value = this.value.replaceAll('.', '').replace(',', '.');
    };
    
    input.onblur = function() {
      this.value = transformValue(this.value);
    };
  }
});

form.onsubmit = function() {
  let inputs = form.querySelectorAll('input[type="text"]');
  for (let i = 0; i < inputs.length; i++) {
    inputs[i].value = inputs[i].value.replaceAll('.', '').replace(',', '.');         }
  for (let i = 0; i < inputs.length; i++) {
    alert('submitted value ' + inputs[i].value);
  }
};
#myForm {
  display: flex;
  flex-direction: column;
}

#myForm input {
  outline: none;
  border: 1px solid #000;
  border-radius: 3px;
  margin: 5px 0;
  padding: 3px 7px;
}
<form id="myForm">
  <input type="text" value="1400.45">
  <input type="text" value="1401.45">
  <input type="text" value="1402.45">
  <input type="submit">
</form>


Source: stackoverflow