javascript – Terceiro IF ELSE

Question:

So I'm a javascript newbie and I was practicing making a function that forces the CPF field scores

function maskCpf(){
var c_char = document.getElementById("txtCpf").value.length
   if (c_char == 3){
document.getElementById("txtCpf").value =   document.getElementById("txtCpf").value + "."
                }else if (c_char == 7){
                    document.getElementById("txtCpf").value = document.getElementById("txtCpf").value + "."

            }else if(c_char = 11){
                    document.getElementById("txtCpf").value = document.getElementById("txtCpf").value + "-"

                }
            }

But that last "else if" doesn't work at all. Anyone Help?

Answer:

You are doing an assignment instead of a comparison.

c_char == 11 

If you allow a hint (it looks like you are a beginner), you repeat the expression over and over again

document.getElementById("txtCpf").value

To make your life easier, code readability, future maintenance and performance as javascript only traverses the DOM tree once (As mentioned by Paulo Gustavo), use variables to store this value:

var textoCpf = document.getElementById("txtCpf").value;

And in the future, when such a situation occurs, try using console.log() with the value of the variable you check to debug 😉

Scroll to Top