Change input class when it is filled in

1

I'm making a form using primefaces, and I wanted my input to change class when it was filled, only returning the previous class if the user deleted the content. This is to make the outputLabel exit from inside the input and be visible as per the figure I attached.

  

The first figure is as it is initially;   The second figure is what it's like to stay;   The third is how it's getting.

Does anyone know a way to do this? Mine here is not working ...

    
asked by anonymous 03.01.2018 / 01:23

2 answers

0

You can check the input blur.

See what class exists on the label when it is on top of the input (with the effect you want) and do the following:

IF YOU ARE USING JQUERY

$('#selector_input').on('blur', function(){
    var _self = $(this);

   if(_self.val() != null){
      $('#selector_label').addClass('class-do-efeito');
   }else{ 
      $('#selector_label').removeClass('class-do-efeito');
   }
})

IF YOU ARE USING PURE JAVASCRIPT

var input = document.getElementById('id_input');
var label = document.getElementById('id_label');

input.onblur = verifyInput(input);

function verifyInput(input){

   if(input.value != null){
      label.classList.add('class-do-efeito');
   }else{
      label.classList.remove('class-do-efeito');
   }
}
    
03.01.2018 / 01:35
0

If you just want to change the class of input (as per question), use oninput ( oninput is more efficient because it detects any changes in the field):

<script>
    var el = document.querySelector("#id_do_input");
    el.oninput = function(){
        this.value ? this.classList.remove('nome_da_class') : this.classList.add('nome_da_class')
    }
</script>

Example:

var el = document.querySelector("#id_do_input");
el.oninput = function(){
   this.value ? this.classList.remove('nome_da_class') : this.classList.add('nome_da_class');
}
.nome_da_class{
  background: yellow;
}
<input placeholder="Nome" type="text" class="nome_da_class" id="id_do_input" />
    
03.01.2018 / 03:08