jQuery detect if textarea is empty

前端 未结 11 919
抹茶落季
抹茶落季 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: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.

提交回复
热议问题