最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

showhide div when input field is empty(jquery, javascript) - Stack Overflow

programmeradmin1浏览0评论

I have a div with content, hide on default and I want to show it, when user input, in the input field which is #control.

<form>
<input name="control" value="" id="control" />
<div class="show_hide">
  //some content here........
</div>
</form>

I have a div with content, hide on default and I want to show it, when user input, in the input field which is #control.

<form>
<input name="control" value="" id="control" />
<div class="show_hide">
  //some content here........
</div>
</form>
Share Improve this question asked Mar 8, 2016 at 4:06 jhunliojhunlio 2,6604 gold badges29 silver badges48 bronze badges 2
  • 2 1. Bind input event on the <input> 2. If entered any value in the textbox, show the <div> else hide it. – Tushar Commented Mar 8, 2016 at 4:07
  • 1 Use $('#control').on('input', function(){ ... }) – Rayon Commented Mar 8, 2016 at 4:07
Add a ment  | 

2 Answers 2

Reset to default 9

// Bind keyup event on the input
$('#control').keyup(function() {
  
  // If value is not empty
  if ($(this).val().length == 0) {
    // Hide the element
    $('.show_hide').hide();
  } else {
    // Otherwise show it
    $('.show_hide').show();
  }
}).keyup(); // Trigger the keyup event, thus running the handler on page load
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
  <input name="control" id="control" />
  <div class="show_hide">
    //some content here........
  </div>
</form>

On keyup check the value of the input if length is 0 meaning empty hide the div otherwise show

Attach input event with #control as shown :-

$('#control').on('input', function(){
   if($.trim(this.value) != "")
      $(this).next('div.show_hide').show();
   else
      $(this).next('div.show_hide').hide();
});

Shorter Versions :-

$('#control').on('input', function(){
    $(this).next('div.show_hide').toggle($.trim(this.value) != "");
});

OR

$('#control').on('input', function() {
  $(this).next('div.show_hide').toggle(this.value.length > 0);
});

OR(adding @Rayon answer in ment here)

$('#control').on('input', function(){
    $(this).next('div.show_hide').toggle(!this.value);
});
发布评论

评论列表(0)

  1. 暂无评论