Javascript - How do "IF and Else" work together with "Returns"?

Asked

Viewed 93 times

1

I’m having a hard time understanding why sometimes, depending on where an "if" statement is inserted into a particular block of a function, it is ignored. And how to use the "retuns", when you want inside these expressions to stop, advance or return a certain function ?

For example:

In this code below, everything happens, as predicted, however, the cursor gets locked in the input and does not advance to another field neither with TAB nor clicking, gets locked in Focus, now in the next example :

function nome_existe() {
	
	if(!valida_nome()) { // caso seja inválido
	document.getElementById("input_nome_cad").focus();
	return;
	}
	var nome = document.getElementById("input_nome_cad").value;
	var xmlreq = CriaRequest();
	xmlreq.open("GET", "mysqli_select_ajax.php?nome_cad=" + nome, true);
	xmlreq.onreadystatechange = function(){
		if (xmlreq.readyState == 4 && xmlreq.status == 200){
	    	document.getElementById("input_nome_cad").value='';
			document.getElementById("input_nome_cad").placeholder = xmlreq.responseText;
		}
		if(document.getElementById("input_nome_cad").placeholder == "Nome já existe!"){
			document.getElementById("input_nome_cad").placeholder = "Troca o nome";
		}
	}
	document.getElementById("input_nome_cad").focus();
	xmlreq.send(null);
	
}

In this example I added a new "if" that is ignored, as these checks work ?

function nome_existe() {
	
	if(!valida_nome()) { // caso seja inválido
	document.getElementById("input_nome_cad").focus();
	return;
	}
	var nome = document.getElementById("input_nome_cad").value;
	var xmlreq = CriaRequest();
	xmlreq.open("GET", "mysqli_select_ajax.php?nome_cad=" + nome, true);
	xmlreq.onreadystatechange = function(){
		if (xmlreq.readyState == 4 && xmlreq.status == 200){
	    	document.getElementById("input_nome_cad").value='';
			document.getElementById("input_nome_cad").placeholder = xmlreq.responseText;
		}
		if(document.getElementById("input_nome_cad").placeholder == "Nome já existe!"){
			document.getElementById("input_nome_cad").placeholder = "Troca o nome";
		}
	}
/*Esse acréscimo parece ser ignorado, o "else" não funciona*/	
	if(document.getElementById("input_nome_cad").placeholder != "Troca o nome"){
		document.getElementById("input_email_cad").focus();
	}else{
		document.getElementById("input_nome_cad").focus();
	}
	xmlreq.send(null);
	
}

valida_name();

function valida_nome(){
	var filter_nome = /^([a-zA-Zà-úÀ-Ú0-9]|\s)+$/ ;
	if(!filter_nome.test(document.getElementById("input_nome_cad").value)){
	document.getElementById("input_nome_cad").value='';
	document.getElementById("input_nome_cad").placeholder = "Nome inválido";
	document.getElementById("input_nome_cad").style.borderColor = "#ff0000";
	document.getElementById("input_nome_cad").style.outline = "#ff0000";
	document.getElementById("input_nome_cad").focus();
	document.getElementById("input_nome_cad").onkeydown = function keydown_nome(){
	document.getElementById("input_nome_cad").style.borderColor = "#999999";
	document.getElementById("input_nome_cad").style.outline = null;
				}
	return false;	
	}
	return true;
}

  • It might help if you put the valida_nome() in the question

  • If you comment on the xmlreq.send(null); (add a // in front), the else works?

  • vc is validating twice, the first one in if(valida_xxx) there has a false or true Return and when entering the if you put a Return. when you place a Return with nothing after it turns true, then regardless of your initial validation if you enter if will always be true.

1 answer

1


Your conditions are being executed before the request ends.

The only thing you need to do is move these conditions to the condition block from where the request ends (e.g., if(xmlreq.readyState === 4...)...). I even reworked just a little code.

function nome_existe() {
    var input = document.getElementById("input_nome_cad")
    if (!/^([a-zA-Zà-úÀ-Ú0-9]|\s)+$/.test(input.value)) {
        input.value = ''
        input.placeholder = "Nome inválido"
        input.style.borderColor = "#f00"
        input.style.outline = "#f00"
        input.onkeydown = function() {
            this.style.borderColor = "#999"
            this.style.outline = null
        }
        input.focus()
        return
    }
    var request = new XMLHttpRequest
    request.open("GET"
           , "mysqli_select_ajax.php?nome_cad=" + input.value
           , true)

    request.onreadystatechange = function() {
        if (request.readyState === 4) {
            if (request.status === 200) {
                input.value = ''
                if (request.response === "Nome já existe!") {
                    input.placeholder = "Troca o nome"
                    input.focus()
                }
                else {
                    input.placeholder = request.response
                    document.getElementById("input_email_cad").focus()
                }
            }
            else {
                /* Erro de requisição. */
            }
        }
    }
    request.send()
}

Browser other questions tagged

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