最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin15PV0评论

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);
});
Post a comment

comment list (0)

  1. No comments so far