2

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?

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

I actually run into a problem because the preexisting code is using input type number and doesn't allow non-number characters. I guess I have to change those fields into text first. Thank you.
Yes, because type="number" inputs already formats the value, adding a comma so it's impossible to display the value in two different formats. Change them to type="text" and forbid non-numeric input. If you have a problem with that please tell me to add it on existing code of the response.
0

The below solution is totally dynamic, as wherever you want to put decimal position.

var num;
$(document).ready(function(){
 num=$(".nums").val();
var nstring=num.replace(/\D/g,'');
var total_strings=nstring.length;
totalz=pad("1", (total_strings)); 
var nums=eval(nstring/totalz);
nums=""+nums+"";
var new_array=nums.split(".");
var val_1=addCommas(new_array[1]);
var narray=new_array[0]+"."+val_1;
$(".nums").val(narray);
});

$(".nums").focus(function(){
var numz=num;
$(".nums").val(numz);
});


$(".nums").blur(function(){
 num=$(".nums").val();
var nstring=num.replace(/\D/g,'');
var total_strings=nstring.length;
totalz=pad("1", (total_strings)); 
var nums=eval(nstring/totalz);
nums=""+nums+"";
var new_array=nums.split("."); 
var val_1=addCommas(new_array[1]);
var narray=new_array[0]+"."+val_1;
$(".nums").val(narray);
});

$(".nums").focus(function(){
var numz=num;
$(".nums").val(numz);
});

$(".form1").submit(function(){
var numz2=num;
$(".nums").val(numz2);
$(".form1").submit();
});


function pad (str, max) {
  str = str.toString();
  return str.length < max ? pad(str+"0", max) : str;
}

function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form1" action="submit.php" method="post">
 <input type="text" name="num" class="nums" value="1.40045">
  <input type="submit">
   </form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.