jQuery detect if textarea is empty

前端 未结 11 849
抹茶落季
抹茶落季 2020-12-25 11:05

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

相关标签:
11条回答
  • 2020-12-25 11:23
    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
    }
    
    0 讨论(0)
  • 2020-12-25 11:24

    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;
      }
    
    0 讨论(0)
  • 2020-12-25 11:24
    $.each(["input[type=text][value=]", "textarea[value=]"], function (index, element) {
                  //only empty input and textarea will come here
    });
    
    0 讨论(0)
  • 2020-12-25 11:26

    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.

    0 讨论(0)
  • 2020-12-25 11:27

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

    if (!$(`#textareaid`).val().length)
    {
         //do stuff
    }
    
    0 讨论(0)
  • 2020-12-25 11:27
    if(!$('element').val()) {
       // code
    }
    
    0 讨论(0)
提交回复
热议问题