1

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>
2
  • 2
    1. Bind input event on the <input> 2. If entered any value in the textbox, show the <div> else hide it. Commented Mar 8, 2016 at 4:07
  • 1
    Use $('#control').on('input', function(){ ... }) Commented Mar 8, 2016 at 4:07

2 Answers 2

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

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

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

1 Comment

@Tushar added explanation. Im not good with english so i seldom explain i sometimes dont explain clear enough
4

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 comment here)

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

3 Comments

Will this hide the input if value is '' ?
Or just $(this).next('div.show_hide').toggle(!this.value); Like this
@RayonDabre... i don't think !this.value will return bool?

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.