WEI A
WEI A

Reputation: 401

How to use jQuery to determine if there is a value in the input box?

Hello everyone ~ I am currently learning jQuery by myself to achieve an effect! I will describe my problem, but my English is not very good, if the description is not good, please forgive me.

What I want to do now is make an input field, and when I press search it will say if the input field has a value in it then the input field will not disappear, if there is no value in it then the input field will disappear.

I have tried to use the following way to write, want to ask whether there is any wrong writing? Because regardless of whether there is a value in the input box, it will disappear. Thanks for watching

$(function(){
  let test = $('.input').val();
  $('.btn').on('click',function(){
   if(test == ""){
     $('.demo').css('display','none');
   }else if(test !== ""){
    $('.demo').css('display','block');
   }
  })
})
.demo{
  display:inline-block;
  padding:10px;
  border:1px solid #ccc;
}

.btn{
  margin-left: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="demo">
  <input type="text" class="input"><button class="btn">搜尋</button>
</div>

Upvotes: 0

Views: 30

Answers (2)

kmoser
kmoser

Reputation: 9308

You are determining the value of the input field only once, before the user interacts with it. You should be checking the value of the input field every time the user clicks the button:

$(function(){
  $('.btn').on('click',function(){
   let test = $('.input').val();
   if(test == ""){
     $('.demo').css('display','none');
   }else if(test !== ""){
    $('.demo').css('display','block');
   }
  })
})

Upvotes: 1

Real Quick
Real Quick

Reputation: 2810

Get your input field value on click, not on load.

    $(function(){
  $('.btn').on('click',function(){
  let test = $('.input').val();
  
   if(test == ""){
     $('.demo').css('display','none');
   }else if(test != ""){
    $('.demo').css('display','block');
   }
  })
})
.demo{
  display:inline-block;
  padding:10px;
  border:1px solid #ccc;
}

.btn{
  margin-left: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="demo">
  <input type="text" class="input"><button class="btn">搜尋</button>
</div>

Upvotes: 1

Related Questions