jQuery 检测 textarea 是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4107404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:40:58  来源:igfitidea点击:

jQuery detect if textarea is empty

jquery

提问by dennismonsewicz

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

如果用户使用 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');
            }
        });

回答by Andy E

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

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

您还可以使用$.trim来确保元素不只包含空格:

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

回答by IlludiumPu36

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

}

回答by BradChesney79

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

问题和答案中的示例表明了 jQuery 的使用,我正在使用 .change listener/handler/whatever 来查看我的 textarea 是否更改。这应该处理手动文本更改、自动文本更改等以触发

//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.

似乎适用于我使用的所有浏览器。http://jsfiddle.net/Q3LW6/。当 textarea 失去焦点时显示消息。

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

更新、更全面的例子:https : //jsfiddle.net/BradChesney79/tjj6338a/

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

使用和报告 .change()、.blur()、.keydown()、.keyup()、.mousedown()、.mouseup()、.click()、mouseleave() 和 .setInterval()。

回答by Chris Kooken

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

您只需要获取 texbox 的值并查看其中是否包含任何内容:

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

回答by Thariama

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.

要确定 textarea 是否为空,我们查看 textarea 文本内容,如果找到一个单一字符,则它不为空。

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. .textContentgets us the textContent of that dom element. With .lengthwe can see if there are any characters present. So the textarea is empty in case that there are no characters inside.

$(#textareaid)为我们获取 textarea jQuery 对象。 $(#textareaid).get(0)获取 dom 节点。我们也可以在document.getElmentById(textareaid)不使用 jQuery 的情况下使用。 .textContent为我们获取该 dom 元素的 textContent。通过.length我们可以查看是否存在任何字符。所以 textarea 是空的,以防里面没有字符。

回答by dennismonsewicz

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');
            }
        });
    }

回答by Manish

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

回答by Neeraj Walia

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

这将检查空的 textarea 并且不会只允许 textarea 中的空格,因为它看起来也是空的。

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

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

回答by 4127157

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 objis the object of your textarea.

obj你的对象在哪里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>

回答by pjammer

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

Andy E 的回答帮助我找到了为我工作的正确方法:

$.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.

!$(element).val()对我来说没有捕捉到一个空的 textarea。但是当与文本结合时,整个爆炸(!)事情确实有效。