输入字段为空时显示/隐藏div(jquery,javascript)

时间:2016-03-08 04:06:31

标签: javascript jquery

我有一个div内容,默认隐藏,我想在用户输入时在输入字段#control中显示它。

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

2 个答案:

答案 0 :(得分:4)

// 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.com/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>

在键盘上检查输入的值,如果长度为0表示空,则隐藏div否则显示

答案 1 :(得分:3)

input事件附加到#control,如下所示: -

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

更短的版本: -

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

或(在评论中添加@Rayon回答)

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