Jarlei Sassi
Jarlei Sassi

Reputation: 35

Issue with hide() and show() jquery

Can anybody help me with this issue?
I'd like to hide inputs that don't have any text in it. But nthing happens. I don't know what I'm doing wrong.

Teste1: <input type="text" value="conteudo1" id="btn1" >
Teste2: <input type="text" id="btn2" >
Teste3: <input type="text" id="btn3" >
Teste4: <input type="text" value="conteudo4" id="btn4" >
Teste5: <input type="text" value="conteudo5" id="btn5" >
Teste6: <input type="text" id="btn6" >


</body>
</html>

<script>

$(document).ready(function() {

    teste();

});

function teste(){
    for (i = 1  ; i < 7 ; i++) {
        if(('#btn'+i).val == 0){
            $('#btn'+i).show();
            else{
                $('#btn'+i).hide();
            }
        }

    }
}


</script>

Upvotes: 1

Views: 36

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

There are multiple issues in your code

  • ('#btn'+i) returns a string, which does not have val property so the condition will never be true, you need to use $('#btn'+i).val()
  • I assume you want to hide both the label and the text, in that case you need to wrap them in an element

You can add a common class to all the elements to make it easier to select them.

Then you need to wrap the label and input in another element so that both can be hidden

$(document).ready(function() {

  teste();

});

function teste() {
  $('input.btn').filter(function() {
    return !!this.value;
  }).parent().hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Teste1: <input type="text" class="btn" value="conteudo1" id="btn1"></span>
<span>Teste2: <input type="text" class="btn" id="btn2"></span>
<span>Teste3: <input type="text" class="btn" id="btn3"></span>
<span>Teste4: <input type="text" class="btn" value="conteudo4" id="btn4"></span>
<span>Teste5: <input type="text" class="btn" value="conteudo5" id="btn5"></span>
<span>Teste6: <input type="text" class="btn" id="btn6"></span>

Upvotes: 0

J.C. Fong
J.C. Fong

Reputation: 546

You make some error in your code. your else{} is in your if{}. Besides, in if statement, $ is missing for calling the element.

function teste(){
    for (i = 1  ; i < 7 ; i++) {
        if($('#btn'+i).val == 0){
            $('#btn'+i).show();
        }else{
            $('#btn'+i).hide();
        }

    }
}

Upvotes: 1

Related Questions