jQuery检测文本区域是否为空

52

我正在尝试使用jQuery确定一个textarea是否为空,如果用户删除了已经预填充在textarea中的内容。

有什么方法可以实现吗?

这是我尝试过的代码,但它不起作用。

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

你的代码中textarea是真实的变量名还是忘了放在字符串限定符中?例如: $("textarea").live(...)。否则你所写的代码应该可以正常工作。你有收到任何错误吗? - Andy E
textarea 是一个变量名。我没有收到任何错误信息…… 我几乎需要将 keydown 事件绑定到 textarea 上。 - dennismonsewicz
如果 textarea 不是一个选择器,那么你应该使用 bind 而不是 live。请参见 http://api.jquery.com/live/#caveats。 - Andy E
@Andy:我在下面放置了我的工作代码。 - dennismonsewicz
12个回答

114
if (!$("#myTextArea").val()) {
    // textarea is empty
}
你还可以使用$.trim来确保元素不仅包含空格:
if (!$.trim($("#myTextArea").val())) {
    // textarea is empty or contains only white-space
}

@jaminator:对我来说运行良好,没有不兼容的代码。如果你已经尝试过它并且它不起作用,那么问题很可能在你的代码中的其他地方。 - Andy E
这段代码适用于Chrome:if (!($.trim($('#ticket-notes-tickets').val())==="")) { ...} - My1
我使用了:!$.trim($('.textAreaTD').text()) - Nuri Ensing

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

}

5

我知道你已经很久没有解决方案了。因此,这是为其他人准备的,他们想了解其他人如何解决相同的常见问题--就像我一样。

问题和答案中的示例表明使用jQuery,并且我正在使用.change监听器/处理程序/任何东西来查看我的文本区域是否发生更改。这应该处理手动文本更改、自动化文本更改等触发事件。

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

        }
    });
});

在我使用的所有浏览器上似乎都可以正常工作。 http://jsfiddle.net/Q3LW6/。当文本区域失去焦点时,消息会显示。

更新、更详细的示例: https://jsfiddle.net/BradChesney79/tjj6338a/

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


4
为了判断文本域是否为空,我们查看文本域的文本内容,如果有一个字符,则不为空。
尝试:
if ($(#textareaid).get(0).textContent.length == 0){
  // action
}
//or
if (document.getElmentById(textareaid).textContent.length == 0){
  // action
}

$(#textareaid) 可以获取到文本框的 jQuery 对象。 $(#textareaid).get(0) 可以获取到 DOM 节点。 我们也可以使用没有 jQuery 的 document.getElmentById(textareaid).textContent 返回该 DOM 元素的文本内容。 通过 .length 我们可以查看是否存在任何字符。 因此,如果文本框内没有字符,则为空。


.text() 不是一个函数。 - mghaoui
请你[编辑]一下这段代码为什么能回答问题的解释?仅仅给出代码是不被鼓励的,因为它们不能教授解决方案。 - Scimonster

3
您只需要获取文本框的值并查看其是否有内容:
if (!$(`#textareaid`).val().length)
{
     //do stuff
}

1
.length 是一个数字,不是一个函数。 - Matt Ball
val()会去除空格吗?如果不会,为了保险起见,我会去除尾部的空格。 - John Giotta

1

这是我的可用代码

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

1
不会捕获粘贴、剪切、拖放等操作。尝试使用我的插件获取更好的解决方案。 - Andy E
谢谢你的帮助建议!我会研究一下这个插件...看起来比我现在做的要好得多。 - dennismonsewicz
@AndyE提供的链接已失效。 - Kjell Rilbe

1
这将检查空的文本区域,同时也不允许只有空格的文本区域,因为那看起来也是空的。
 var txt_msg = $("textarea").val();

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

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

0

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

这个 !$(element).val() 对于空的文本区域没有起作用,但是和文本结合使用时整个感叹号(!)确实有效。


0

你可以尝试这个方法,大多数情况下应该可以解决问题。如果我有错误,请随时指正:

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

其中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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接