dennismonsewicz
dennismonsewicz

Reputation: 25552

jQuery detect if textarea is empty

I am trying to determine if a textarea is empty if a user deletes what is already pre-populated in the textarea using jQuery.

Anyway to do this?

This is what I have and its not working

$(textarea).live('change', function(){
            if($(this).val().length == 0) {
                $(submitButtonClass).addClass('disabled_button');
                $(submitButtonClass).removeClass('transSubmit');
            } else {
                $('.disabled_button').addClass('transSubmit').css({
                    'cursor':'pointer'
                }).removeClass('disabled_button');
            }
        });

Upvotes: 52

Views: 116040

Answers (12)

kintsukuroi
kintsukuroi

Reputation: 1479

Checking for $("#element).val() === false or !$("#element).val() did not work for me.

Instead, this worked:

// Check if element is empty
if ($("#element").val() === "") {
    // Element is empty! Do stuff here
}

Upvotes: 0

4127157
4127157

Reputation: 1458

You can simply try this and it should work in most cases, feel free to correct me if I am wrong :

function hereLies(obj) { 
  if(obj.val() != "") { 
    //Do this here 
  }
}

Where obj is the object of your textarea.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<textarea placeholder="Insert text here..." rows="5" cols="12"></textarea>
<button id="checkerx">Check</button>
<p>Value is not null!</p>

<script>
  $("p").hide();
  $("#checkerx").click(function(){
      if($("textarea").val() != ""){
        $("p").show();
      }
      else{
       $("p").replaceWith("<p>Value is null!</p>");
      }
  });

</script>
</body></html>

Upvotes: 0

BradChesney79
BradChesney79

Reputation: 678

I know you are long past getting a solution. So, this is for others that come along to see how other people are solving the same common problem-- like me.

The examples in the question and answers indicates the use of jQuery and I am using the .change listener/handler/whatever to see if my textarea changes. This should take care of manual text changes, automated text changes, etc. to trigger the

//pseudocode
$(document).ready(function () {
    $('#textarea').change(function () {
        if ($.trim($('#textarea').val()).length < 1) {

            $('#output').html('Someway your box is being reported as empty... sadness.');

        } else {

            $('#output').html('Your users managed to put something in the box!');
            //No guarantee it isn't mindless gibberish, sorry.

        }
    });
});

Seems to work on all the browsers I use. http://jsfiddle.net/Q3LW6/. Message shows when textarea loses focus.

Newer, more thorough example: https://jsfiddle.net/BradChesney79/tjj6338a/

Uses and reports .change(), .blur(), .keydown(), .keyup(), .mousedown(), .mouseup(), .click(), mouseleave(), and .setInterval().

Upvotes: 5

Neeraj Walia
Neeraj Walia

Reputation: 228

This will check for empty textarea as well as will not allow only Spaces in textarea coz that looks empty too.

 var txt_msg = $("textarea").val();

 if (txt_msg.replace(/^\s+|\s+$/g, "").length == 0 || txt_msg=="") {
    return false;
  }

Upvotes: 1

Manish
Manish

Reputation: 11

if(!$('element').val()) {
   // code
}

Upvotes: 1

Thariama
Thariama

Reputation: 50840

To find out if the textarea is empty we have a look at the textarea text content and if there is one sinlge character to be found it is not empty.

Try:

if ($(#textareaid).get(0).textContent.length == 0){
  // action
}
//or
if (document.getElmentById(textareaid).textContent.length == 0){
  // action
}

$(#textareaid) gets us the textarea jQuery object. $(#textareaid).get(0) gets us the dom node. We could also use document.getElmentById(textareaid) without the use of jQuery. .textContent gets us the textContent of that dom element. With .length we can see if there are any characters present. So the textarea is empty in case that there are no characters inside.

Upvotes: 4

IlludiumPu36
IlludiumPu36

Reputation: 4304

if (!$.trim($("element").val())) {

}

Upvotes: 10

iswok
iswok

Reputation: 39

$.each(["input[type=text][value=]", "textarea[value=]"], function (index, element) {
              //only empty input and textarea will come here
});

Upvotes: 0

pjammer
pjammer

Reputation: 9577

Andy E's answer helped me get the correct way to working for me:

$.each(["input[type=text][value=]", "textarea"], function (index, element) {
if (!$(element).val() || !$(element).text()) {
 $(element).css("background-color", "rgba(255,227,3, 0.2)");
}
});

This !$(element).val() did not catch an empty textarea for me. but that whole bang (!) thing did work when combined with text.

Upvotes: 0

dennismonsewicz
dennismonsewicz

Reputation: 25552

Here is my working code

function emptyTextAreaCheck(textarea, submitButtonClass) {
        if(!submitButtonClass)
            submitButtonClass = ".transSubmit";

            if($(textarea).val() == '') {
                $(submitButtonClass).addClass('disabled_button');
                $(submitButtonClass).removeClass('transSubmit');
            }

        $(textarea).live('focus keydown keyup', function(){
            if($(this).val().length == 0) {
                $(submitButtonClass).addClass('disabled_button');
                $(submitButtonClass).removeClass('transSubmit');
            } else {
                $('.disabled_button').addClass('transSubmit').css({
                    'cursor':'pointer'
                }).removeClass('disabled_button');
            }
        });
    }

Upvotes: 1

Chris Kooken
Chris Kooken

Reputation: 33938

You just need to get the value of the texbox and see if it has anything in it:

if (!$(`#textareaid`).val().length)
{
     //do stuff
}

Upvotes: 3

Andy E
Andy E

Reputation: 344783

if (!$("#myTextArea").val()) {
    // textarea is empty
}

You can also use $.trim to make sure the element doesn't contain only white-space:

if (!$.trim($("#myTextArea").val())) {
    // textarea is empty or contains only white-space
}

Upvotes: 114

Related Questions