earthyearth
earthyearth

Reputation: 15

how to remove an element when textarea is empty?

I want to check if the textarea is empty and then remove the element prev() to it. How do I do so? My attempt was this:

if($(".inputs").val().length == 0){
  $(this).prev().hide();
};

Do I have to check for "keypress"? The element I am trying to hide was show() after a "keypress" event. But I want to hide it immediately if the textarea is empty.

Edit: Question 2: I was using this code to show an element after first input:

 $(".inputs").one("keypress", function(){
   $(this).prev().show().addClass("animated slideInUp");
 });

but now that I want to hide and show depending on the length of the textarea should I do something like this:

  $(".inputs").on("input", function() {
if ($(".inputs").val().length == 0) {
  $(this).prev().hide();
}
else if ($(".inputs").val().length == 1) {
  $(this).prev().show().addClass("animated slideInUp");
}

Upvotes: 0

Views: 92

Answers (1)

Obsidian Age
Obsidian Age

Reputation: 42314

If you want to hide the previous element when you delete content within the <textarea>, then .keyup is the way to go:

$(".inputs").on("input", function() {
  if ($(".inputs").val().length == 0) {
    $(this).prev().hide();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">Hidden when all content is deleted, doesn't restore</div>
<textarea class="inputs"></textarea>

Keep in mind that this won't restore the previous element when you start typing again. If you'd like to do that, you'll need to extend the script a little to also .show() the previous element:

$(".inputs").on("input", function() {
  if ($(".inputs").val().length == 0) {
    $(this).prev().hide();
  }
  else {
    $(this).prev().show();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">Hidden when all content is deleted, restores</div>
<textarea class="inputs"></textarea>

Note that input is used over keyup in case the user edits the field without using the keyboard.

Hope this helps! :)

Upvotes: 2

Related Questions