Third IF ELSE

3

So I am a beginner in javascript and I was practicing doing 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 + "-"

                }
            }

It's just that this "else if" does not work at all. Someone Help?

    
asked by anonymous 14.01.2017 / 22:04

3 answers

2

You are making an assignment instead of a comparison.

c_char == 11 

If you allow a hint (it seems that you are a beginner), you repeat the expression several times

document.getElementById("txtCpf").value

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

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

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

    
14.01.2017 / 22:33
0

I do not know if you noticed but the third ELSE IF in the condition is missing another equal sign (=). Try changing and see if it worked.

    
15.01.2017 / 01:36
0

In the third condition you are assigning the value 11 to c_char. The correct is to compare (==).

Another tip I use a lot is to put "console.log" under the conditions, to see what time the code stops, or where it does not go in.

For example:

else if(c_char = 11){
   console.log(c_char); //retorna valor de c_char
   console.log("Entrou aqui.");
   document.getElementById("txtCpf").value = document.getElementById("txtCpf").value + "-"
}
    
16.01.2017 / 11:20