Formatear cedula

mail@pastecode.io avatar
unknown
html
2 years ago
1.5 kB
2
Indexable
Never
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input id="ciField">
</body>
<script>
    let ciField = document.getElementById("ciField");
    ciField.value = "";
    const dotCi = (ci) => (Math.round(parseInt(ci) * 100) / 100).toLocaleString("es-UY");

    ciField.addEventListener("keyup", (e) => {
        var charCode = (e.which) ? e.which : e.keyCode;
        if ((charCode >= 48 && charCode <= 57) || (charCode >= 96 && charCode <= 105)) {
            let strCi = e.target.value;

            if (!strCi.trim().length) {
                ciField.value = "";
                return;
            }

            strCi = strCi.replace(".", '');
            strCi = strCi.replace("-", '');
            
            if (strCi.length > 6) {
                strCi = strCi.substring(0, strCi.length);
                let lastDigit = strCi[strCi.length -1];

                let dotted = dotCi(strCi.substring(0, strCi.length -1));
                if (dotted) {
                    ciField.value = dotted + "-" + lastDigit;
                    return;
                } else {
                    ciField.value = "";
                    return;
                }
            } else {
                ciField.value = dotCi(strCi);
                return;
            }
        }
    })
</script>

</html>