Ayumi Takanashi
Ayumi Takanashi

Reputation: 53

How to hide a button if a textarea gets empty and show the button as soon as it's not empty anymore?

My jQuery code:

$(document).ready(function(){

    var textboxHomeValue = $('#post-textbox textarea');

    $(document).on('keyup, keydown', '[data-listener="textboxHome"]', textboxHome);
    function textboxHome(e) {
        if($.trim(textboxHomeValue).length > 0){
            $('#post-button-disabled').hide();
            $('#post-button').show();
        } else {
            $('#post-button-disabled').show();
            $('#post-button').hide();
        }
    }
});

The beginning works fine. As soon as I type something into the textarea, the button shows up but if I delete the text it won't disappear again.

Upvotes: 0

Views: 980

Answers (3)

SilentCoder
SilentCoder

Reputation: 2000

Check this,

//Initially hide button
$('#btn').hide();

//Textarea keyup function
$('textarea[name=txtarea]').keyup(function(){
  if($.trim($(this).val()).length  <= 0)$('#btn').hide()
  else $('#btn').show()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<textarea name="txtarea"></textarea>
<button  id ="btn">Button</button>

Upvotes: 0

Zenoo
Zenoo

Reputation: 12880

You need to $.trim the value of your textarea, not the jQuery object containing your textarea :

$(document).on('keyup', 'textarea', function() {
  if ($.trim($(this).val()).length == 0) {
    $('button').show();
  } else {
    $('button').hide();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
<button>I'm only here if the textarea is empty !</button>

Upvotes: 1

Julian
Julian

Reputation: 3859

Try to use the jQuery change Method

$("#yourTextarea").change(function(){
    //Check if empty or not and hide button if needed
});

To call your function:

$("#yourTextarea").change(textBoxHome);

Upvotes: 0

Related Questions