Mascara for weight

3

Searching the internet, I found a code that makes weight masks in the field. But this code works with ID criteria.

I would like it to work with CLASS, so I can use it in other fields.

function id(el){
        return document.getElementById(el);
}
window.onload = function(){
        id('peso').onkeyup = function(){
            var v = this.value,
                integer = v.split('.')[0];


            v = v.replace(/\D/, "");
            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;
        }
};
    
asked by anonymous 14.05.2015 / 17:55

3 answers

3

I imagine that your problem dynamically includes fields genaros, and hence you need to use delegation. My suggestion is:

function mascara() {
    var v = this.value, integer = v.split('.')[0];
    v = v.replace(/\D/, "");
    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;
}
$('#elementoPai').on('keyup', '.peso', mascara);

If you add more information about how you want to format the output, we can help you adapt the mask.

    
14.05.2015 / 18:01
1

Instead of

function id(el){
    return document.getElementById(el);

}

Place

function id(el){
   return document.getElementsByClassName(el);
}

And put a class with the name 'weight' in your element.

    
14.05.2015 / 17:57
1

You can directly use jQuery for this if you are not using dynamically generated fields:

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

    v = v.replace(/\D/, "");
    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;
});

I also suggest changing the line

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

for

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

To remove the letters correctly.

    
14.05.2015 / 18:10