0

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>

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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');
   }
  })
})

1 Comment

thank you for your help, i have gained a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.