How to input weight mask using Javascript

Asked

Viewed 3,826 times

1

So far I’m trying like this, but it didn’t work:

$('.peso').keyup(function () {
var v = this.value,
integer = v.split('.')[0];

v = v.replace(/\D/g, "");

v = v.replace(/^[0]+/, "");

if (v.length <= 3 || !integer) {

if (v.length === 1) v = '0.00' + v;

if (v.length === 2) v = '0.0' + v;

if (v.length === 3) v = '0.' + v;
} else { v = v.replace(/^(\d{1,})(\d{3})$/, "$1.$2");}
this.value = v;});

HTML:

<p><label>Capacacidade</label></p>
<div class="input-group has-success">
<input type="text" name="txtcapac" placeholder="Capacidade em Kg" class="peso form-control"/>
<div class="input-group-addon"><span>Kg</span></div>
  • 4

    You have already tried using jquery.Mask?

  • That one? Function mascara(t, Mask){ var i = t.value.length; var output = Mask.substring(1,0); var text = Mask.substring(i) if (text.substring(0,1) != output){ t.value += text.substring(0,1); } ; }

  • The plugin same, I will post an example as answer

2 answers

3


  • It hasn’t worked yet, I think I’m doing something wrong. <script type="text/javascript"> $(Document). ready(Function() { $('.weight').Mask("#0.000", {Reverse: true}); }) </script>

  • that’s all?

  • You could check in the browser console if any error is appearing?

  • Uncaught Syntaxerror: Unexpected token < cadastro_equipamento.html:44 Uncaught Typeerror: $(...). Mask is not a Function

  • You added the jquery.Mask script to your code?

  • 'cause I didn’t add, the only thing I added was the code I typed before

  • but how do I do it? I am very lay in javascript

  • It’s up to you download the plugin on github and then add your project folder and link to the tag <script type="text/javascript" src="localdoscript"></script>

  • thanks for your help and patience, it’s working fine now. vlw

Show 4 more comments

-2

I’m getting...thanks friend! galley was show...

$('.weight'). keyup(Function() { var v = this.value, integer = v.split('.')[0];

v = v.replace(/\D/g, "");

v = v.replace(/^[0]+/, "");

if (v.length <= 5 || !integer) {

    if (v.length === 5) v =  v.substring(0,2) + '.' + v.substring(2,5) ;

    if (v.length === 4) v = '0' + v.substring(0,1) + '.' + v.substring(1,4) ;

    if (v.length === 3) v = '00.' + v;
    
    if (v.length === 2) v = '00.0' + v;
    
    if (v.length === 1) v = '00.00' + v;
    
} else {
    //  v = v.replace(/^(\d{2,})(\d{3})$/, "$1.$2");
    if (v.length > 5 || !integer) {
        v =  v.substring(0,2) + '.' + v.substring(2,5) ;
    }
}
select.value = v;

});

in html....

Weight Bag(kg)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.