JS - Lock button when inputs do not meet a requirement

Asked

Viewed 32 times

-2

Well, I’m trying to block a button when the inputs are not filled in the form but I can’t, I’ve seen several examples of code that worked but even when I try to copy, they make the same mistake. Uncaught Typeerror: Cannot read Property 'addeventlistener' of null

html

    <fieldset id="fie">

    <legend>LOGIN</legend>
    <div class='campo'>
        <label for="login">Nome:</label>
        <input type="text" name="login" id="login" required>
    </div>

    <div class="campo">
        <label for="senha">Senha:</label>
        <input type="password" name="senha" id="senha" required>
    </div>
    
    <button type="submit" class="btn" >Login</button>

    </fieldset>    

Javascript

  let btn = document.querySelector('btn');
  let login = document.querySelector('login');
  let senha = document.querySelector('senha');

  login.addEventListener('keyup', verificar(login));
  senha.addEventListener('keyup', verificar(senha));

  function verificar(verificado){

      if(verificado.value.lenght < 3 ){
          btn.disabled = true;
      }else{
          btn.disabled = false;
      }

  }

  • 1

    The querySelector method accepts a micro-language similar to jQuery. I believe you want to select elements by class, so you have to put a dot in front of each name e.g. querySelector('.btn'). If you were to select by id you would have to put the # in front.

1 answer

-1


The error is happening because the selector is not finding the desired input and returning the value as "null", to solve just add a "." before the selectors to understand that they are searching for the element by the class. For example, let login = document.querySelector('.login');

For your code to work the way you want, you can use the onkeyup in the two input to call a single function that validates whether the two fields are more than 3 characters long.

I modified your html a little bit and changed the logic of your script. I will comment on the changes so you understand better. Follow:

HMTL:

<fieldset id="fie">
    
    // Para ambos os inputs, adicionei uma classe para encontrar o input pelo querySelector,
    // e adicionei "onkeyup" para chamar a função "validaCampo()" quando pressionado alguma tecla.
    <legend>LOGIN</legend>
    <div class='campo'>
        <label for="login">Nome:</label>
        <input type="text" name="login" id="login" class="login" required onkeyup="validaCampo()">
    </div>          

    <div class="campo">
        <label for="senha">Senha:</label>
        <input type="password" name="senha" id="senha" class="senha" required onkeyup="validaCampo()"> 
    </div>
    
    <button type="submit" id="btn" class="btn" >Login</button>

</fieldset>

Script:

 let btn   = document.querySelector('.btn');   //coloquei um "."  para localizar pela classe "btn"
 let login = document.querySelector('.login'); //coloquei um "."  para localizar pela classe "login"
 let senha = document.querySelector('.senha'); //coloquei um "."  para localizar pela classe "senha"

 btn.disabled = true; // Aqui setei inicialmente o botão como "disabled" fora da function,
                      // ou seja, quando carregamos o site o botão é desabilitado.

 function validaCampo(){
      // A condição é a seguinte: Para liberar o botão, os dois campos precisam
      // possuir mais de 3 caracteres.
    if(login.value.length > 3 && senha.value.length > 3){
        
        btn.disabled = false; // Então aqui habilitamos o botão.

    }else {
     // Caso apagamos algum caractere, e passar a ter 3 ou menos, ele desabilita o botão novamente.
        btn.disabled = true; 
    
    }
  }

Browser other questions tagged

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