I need to compare variables with the lack of information

Asked

Viewed 27 times

0

I am creating a form and need to alert the user when a field is not filled. I am trying to use the if to make this comparison, I have tried to compare with null and it did not work. my code is like this:

function Cadastrar(){

    var titulo = document.getElementById("titulo").value;
    var editora = document.getElementById("editora").value;
    var conteudoTabela = document.getElementById("livros_cadastrados");
    var novaLinha = document.createElement("tr");

    if(titulo == null || editora == null){
        alert("Dados incompletos");
    }else{
        novaLinha.innerHTML = "<td>" + titulo + "</td><td>" + editora + "</td><td><a href='' class='botaoExcluir'>Excluir</a>";
        conteudoTabela.appendChild(novaLinha);
        alert("Novo livro cadastrado:" + "\n" + titulo);
    }        
}

I’m quite a beginner, so if possible, I’d like a very detailed explanation. Thank you very much!

  • Where are you calling that function Cadastrar?

1 answer

1


Friend, I believe you can do it this way:

Function Register(){

var titulo = document.getElementById("titulo").value;
var editora = document.getElementById("editora").value;
var conteudoTabela = document.getElementById("livros_cadastrados");
var novaLinha = document.createElement("tr");

if(titulo == '' || editora == ''){
    alert("Dados incompletos");
}else{
    novaLinha.innerHTML = "<td>" + titulo + "</td><td>" + editora + "</td><td><a href='' class='botaoExcluir'>Excluir</a>";
    conteudoTabela.appendChild(novaLinha);
    alert("Novo livro cadastrado:" + "\n" + titulo);
}        

}

If your intention is just to check that the fields are empty, you use the check by '' as it is how you put the condition whether the field is empty or not. Leave as null I believe it does not work or if it works, it would not be the best way. It will also depend a little on how and where you call this function, if it is something in onsubmit or onchange even with onblur and onfocusout. If applicable, put your HTML code in as well.

Browser other questions tagged

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