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 it is desired within that expressions to stop, forward or return a certain function?
For example:
In this code, everything happens, as expected, however, the cursor is locked in the input and does not advance to another field with TAB or clicking, is 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, how do 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;
}