Masking value in input [duplicate]

0

I would like to do the following, the user types 1, the input would have the value , 01 , then he would type 2, it would appear , 12 , then he would type 3, would appear 1.23 , so on. I have the input as follows:

 <input type="text" class="form-control"  id ="produto_preco_unitario" name="produto_preco_unitario"
                         value="" placeholder="Preço por Unidade" required/>
    
asked by anonymous 25.03.2017 / 01:39

1 answer

0

var mask = {
 money: function() {
 	var el = this
 	,exec = function(v) {
 	v = v.replace(/\D/g,"");
 	v = new String(Number(v));
 	var len = v.length;
 	if (1== len)
 	v = v.replace(/(\d)/,"0.0$1");
 	else if (2 == len)
 	v = v.replace(/(\d)/,"0.$1");
 	else if (len > 2) {
 	v = v.replace(/(\d{2})$/,'.$1');
 	}
 	return v;
 	};

 	setTimeout(function(){
 	el.value = exec(el.value);
 	},1);
 }

}

$(function(){
 $('input').bind('keypress',mask.money)
});
<script src="http://code.jquery.com/jquery-1.8.3.min.js"type="text/javascript"></script>
 <input type="text" class="form-control"  id ="produto_preco_unitario" name="produto_preco_unitario"
                     value="" placeholder="Preço por Unidade" required/>

You can also use with thousands separator

$(function () { //ready
    $("#produto_preco_unitario").maskMoney();
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"type="text/javascript"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"type="text/javascript"></script>
    
<input type="text" id="produto_preco_unitario" value="" />

The file gets caught in github jquery.maskMoney.js

If you want to change the currency to the Portuguese format (decimal point and thousand point separator) do so:

$(function () { //ready
    $("#produto_preco_unitario").maskMoney({thousands: ".", decimal: ","});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"type="text/javascript"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"type="text/javascript"></script>
    
<input type="text" id="produto_preco_unitario" value="" />
    
25.03.2017 / 03:22