HTML element does not become visible

Asked

Viewed 1,182 times

5

I have the following HTML:

<form action="cadastro/cadastrando.php" method="post">
    <div class="elemf">
        <label>Nome</label>
        <input id="nome" type="text" name="nome" maxlength="15"/>
        <p class="nome_erro">Campo Obrigatório. São permitidos letras e acentos.</p>
    </div>
</form>

When I take the focus of the text field and it is empty, the message that is with the class should appear 'nome_erro'. However it does not appear, it seems that the code executes the method below, but does not change the value of the attribute display, continuing 'none'.

Follows the CSS:

.erro {
    font: 12px Verdana, Arial, Helvetica, sans-serif;
    color: #ff0000;
    left: 10px;
    display: inline-block;
}
.nome_erro {
    display: none;
}

And Javascript:

$(document).on('blur','input, textarea, select', function() {
    if($(this).val() === '') {
        switch($(this).attr('id')) {
            case 'nome':
                $('.nome_erro').addClass('erro');
                break;
        }
    } else {
        switch($(this).attr('id')) {
            case 'nome':
                $('#nome_erro').removeClass('erro');
                break;
        }
    }
});

5 answers

10


You have a conflict of priorities. Use so:

display: inline-block !important;

The !important force the display to be inline-block, overlapping none

Online example: http://jsfiddle.net/uY2eq/


Note: As Leofelipe pointed out and well, I also changed in the second switch the ID indicator # for class ., that is to say of

$('#nome_erro').removeClass('erro'); 

for

$('.nome_erro').removeClass('erro');
  • 1

    Still missing is the change @Leofelipe commented on in his reply. Switch selector to # for . in Else .

  • Actually, the conflict was taking place, but the strange thing is that in other places of the project that I’m doing, I wasn’t with this problem, in a strange way

  • 1

    that part of # and . was that I forgot to undo the changes before posting the question

  • Remembering that the statement !important is discouraged as it can generate unwanted effects and "complex" style errors in projects with many lines / CSS files.

4

The answers of Sergio and Leofelipe are correct. For my part I will propose a different way of doing the same thing, with less code:

var nome_erro = $(".nome_erro");
$("#nome").blur(function () {
    nome_erro.toggle(!this.value);
});

The first line transforms the element into a variable, so you do not execute a query with each Blur execution. This improves performance.

  • 1

    Can only use: !this.value. Good optimization +1

  • @Sergio is right. I like short and simple code, I will switch to this form.

3

1º) Your remove Class is setting #error name_error and should be . error name_error.

2º) I usually use . show() and . Hide(). Example:

$('.nome_erro').hide();

if($(this).val() === ''){
    switch($(this).attr('id')){
        case 'nome':
            $('.nome_erro').show(); break;
    }
}
else{
    switch($(this).attr('id')){
        case 'nome':
            $('.nome_erro').hide(); break;
    }
}

1

I noticed that in your code you are validating all fields input,select ..., there is a problem in this, if there were no mandatory fields, this will bring you problems, if you intend to create your own validate, I will leave a hint, only didactic, that you can take as a basis and implement it.

Form

<form name="form" id="form">
   <label for="nome">Nome <small>(obrigatório)</small></label>
   <input type="text" name="nome" data-required="true" />
   <small class="erro">Nome obrigatório</small>
   <label for="end">Endereço <small>(Não obrigatório)</small></label>
   <input type="text" name="end"/>
   <label for="end">Mensagem <small>(Obrigatório)</small></label>
   <textarea name="msg" data-required="true"></textarea>
   <small class="erro">Mensagem obrigatória</small>
   <button type="submit">Enviar</button>
</form>

CSS

label,input,textarea,button{display: block;}
small.erro {display:none; color:red;}

Jquery

$.validate = {
    classErro: '.erro', //classe padrão de exibição de erros
    start: function(form){ // função para inicializar a validação
        //testa todos os campos que tiverem o atributo data-required
        $(form+' *[data-required]').on('blur',function(){
            if ($(this).val() == ''){ // se o campo estiver vazio, mostra erro
                $(this).next($.validate.classErro).show();
            } else { 
                $(this).next($.validate.classErro).hide(); 
            }
        });
        $(document).ready(function(){
           //testa o form no momento do submit
           $(form).submit(function(event){
               if(!$.validate.validSubmit(form)){
                   //se não passar na validação impede o submit
                   event.preventDefault();
               }
           });
        });
      },
      //função para validar no momento do submit
      validSubmit: function(form){
         // procura por campos com attr required
         $(form+' *[data-required]').each(function(){ 
             if ($(this).val() == ''){
                 $(this).next($.validate.classErro).show();
             } else { 
                 $(this).next($.validate.classErro).hide(); 
             }
         });
         // se houver erro retorna falso
         if($(form+' small.erro:visible').length > 0){ 
             return false;
         }
         return true;
       }
  };

// inicia a função passando como parametro o id do form
$.validate.start('#form'); 

Example: Jsfiddle

Based on this example, you can create other functions to validate for example:

  • Dates
  • Email
  • Telephone
  • CPF and CPNJ

Among others, good luck!

1

CSS respects the law of superscription, that is, what comes last is that it has priority. So the solution would be to reverse the order of the classes:

.nome_erro {
    display: none;
}
.nome_erro.erro {
    font: 12px Verdana, Arial, Helvetica, sans-serif;
    color: #ff0000;
    left: 10px;
    display: inline-block;
}

Example: FIDDLE

Browser other questions tagged

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