Third IF ELSE

Asked

Viewed 85 times

3

So, I’m a beginner in javascript and I was practicing doing a function that forces the scores of the CPF field

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 + "-"

                }
            }

Only this last "if" doesn’t work at all. Anyone Help?

  • 2

    = versus ==

  • This link may be useful: https://www.codecademy.com/en/forum_questions/558ea4f5e39efed371000508

3 answers

3

You’re doing an assignment instead of a comparison.

c_char == 11 

If you allow a hint (it looks like you’re a beginner), Oce repeats the expression many times

document.getElementById("txtCpf").value

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

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

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

  • 1

    It is worth remembering that this tip to catch only once the value of "Document.getElementById("txtCpf")" is not only to improve maintenance, it also serves to improve performance, since the code will only go through once the DOM tree in search of this element

  • Well remembered @Paulogustavo, I will edit in reply

0

I don’t know if you noticed but in the third ELSE IF the condition is missing another equal sign ( = ) . Try to change and see if it worked.

-1

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" in the conditions, to see what time the code stops, or where it does not enter.

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 + "-"
}

Browser other questions tagged

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