Remove div if input is empty

Asked

Viewed 151 times

1

I’d like to rule that out div if the input receive an empty value.

<div class="form-group col-md-2 usuario">
    <label>Usuário:</label>
      <input type="text" readonly class="form-control-plaintext" 
             id="usuario" value="<?php echo $rows['usuario']; ?>"
      >
</div>

I tried to use the JQuery, but excludes even if the field is filled in.

if ('input[value=""]') {
    $('.usuario').remove();
}
  • faltou say at what moment you want to do this, is an event onclick, onblur etc ... at what moment you wish to do so?

  • When the page loads.

2 answers

0


I’m going to show you another way to do this, a little clearer and that might bring you more knowledge about logic.

var inputValue = $('#usuario').val()

// so ira entrar no IF se o valor for nulo/vazio etc.
if (!inputValue) {
  $('.usuario').remove()
}

I hope I’ve helped!

  • Exactly what I was looking for. Thank you!

0

In fact, your condition is not being compared correctly.

To do this the right way just use this script:

// Primeiro você precisa capturar o valor
var inputUsuario = $('#usuario').val();

// Agora é feita a condição (nulo/vazio)
if(!inputUsuario){
    $('.usuario').fadeOut();
}else{
    // Fiz este else pois caso você precise verificar em tempo real se há usuário, 
    // terá um efeito de fade in.
    $('.usuario').fadeIn();
}

Before you put this into your code, try to understand the logic behind it. Anything, just comment ;)

I hope I’ve helped.

Browser other questions tagged

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