How do I use Javascript to check if my input has any written text?

Asked

Viewed 82 times

-1

I tried it this way:

function aviso() {
  document.querySelector(".registers_button")
  let email_box = document.querySelector(".email")
  if (email_box.innerHTML == '') {
    alert("Por favor, preencha os campos obrigatórios")
  } else if (!email_box.innerHTML == '') {
    alert("Redirecionando...")
  }
}
<p class="email_text"> E-mail: <input class="email" type="text" placeholder="Ex: [email protected]"> </p>

  • Don’t let your <input> with <p> use <label>. Ex: <label class="email_text"> E-mail: <input class="email" type="text" placeholder="Ex: [email protected]"> </label>. Also see <input type="email">

  • Opa buddy, thank you very much, I will make this change in my code. Gradually I will learn HTML semantic.

3 answers

2

Your question needs further clarification, but assuming your element with the "email" class is an input and not an element like DIV, the correct way to fetch the field value is by using value, not innerHTML

if (email_box.value == '') {
    alert ("Campo vazio");
} else {
    alert("Redirecionando")
}

innerHTML and innerText are properties of elements such as <div>, <p> etc..

  • Man, thank you so much ! your answer was exactly what I was looking for. As for the question, I really need to improve.

  • if the answer is in accordance with what you were looking for mark it as "Answer accepted" =)

1

Your code has two tags one p and a input:

If you want to get the text inside the <p> (an Htmlelement) you can use the innerText:

let txt = globalThis.document.querySelector("p.email_text").innerText
console.log("RESULTADO:", txt);
<p class="email_text"> E-mail: <input class="email" type="text" placeholder="Ex: [email protected]"> </p>


<input class="email" type="text" placeholder="Ex: [email protected]">

If you want to get a text inside a input (Htmlinputelement), you can use the value.

let txt = globalThis.document.querySelector("input.email").value
console.log("RESULTADO:", txt);
<p class="email_text"> E-mail: <input class="email" type="text" placeholder="Ex: [email protected]" value="um valor"> </p>

0

Simpler yet:

if (!email_box.value) {
    return console.log("Campo vazio!")
}

Empty fields are false in Javascript.

If you do a check by placing only the value on if:

if (valor) {
 // faça alguma coisa
}

You’re checking if it’s a value true or not. In that you decide what to do with it.

The exclamation mark is to check if the value is otherwise in the case true. Would equal:

if(email_box.value !== true) {
    return console.log("Campo vazio!")
}

I hope I’ve helped!

  • 1

    Empty fields are false in Javascript, I think you mean values falsy and not the boolean false.

  • Exactly what I meant haha

Browser other questions tagged

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