HTML element does not become visible

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 focus from the text field and it is empty, the message that is with the 'nome_erro' class should appear. However it does not appear, it seems that the code executes the method below but does not change the value of the display attribute, continuing 'none' .

Follow the CSS:

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

And the 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;
        }
    }
});
    
asked by anonymous 05.06.2014 / 15:52

5 answers

9

You have a conflict of priorities. Use this:

display: inline-block !important;

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

Example online: link

Note: As LeoFelipe pointed out well, I also changed the% ID% indicator to switch , that is,

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

for

$('.nome_erro').removeClass('erro');
    
05.06.2014 / 16:08
4

Sergio and LeoFelipe's answers are correct. For my part I 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 at each blur execution. This improves performance.

    
05.06.2014 / 16:13
3

1st) Your remove Class is set to #error_name and should be .error_name.

2nd) 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;
    }
}
    
05.06.2014 / 16:09
1

I noticed that in your code you are validating all fields input,select ... , there is a problem in this, if there were fields not mandatory, this will cause problems, if you intend to create your own validate, just didactic , which you can take as a foundation 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
  • Phone
  • CPF and CPNJ

Among others, good luck!

    
05.06.2014 / 21:16
1

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

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

Example: FIDDLE

    
15.06.2014 / 06:22