How to get value from the textarea field when it's not equal "".

I tried this code, but when I enter text into textarea the alert() isn't works. How to fix it?

<textarea name="textarea" placeholder="Enter the text..."></textarea>

$(document).ready(function () {
    if ($("textarea").value !== "") {
        alert($("textarea").value);
    }

});

推荐答案

Use .val() to get value of textarea and use $.trim() to empty spaces.

$(document).ready(function () {
    if ($.trim($("textarea").val()) != "") {
        alert($("textarea").val());
    }
});

或者,以下是我为干净代码所做的,

$(document).ready(function () {
    var val = $.trim($("textarea").val());
    if (val != "") {
        alert(val);
    }
});

演示:http://jsfiddle.net/jVUsZ/

Jquery相关问答推荐

提交表单时运行自定义验证脚本

我在自定义 WordPress 插件中使用 ajax 时收到错误请求

在 div 中找到第一次出现的类

jQuery 与 ExtJS

jQuery ajax() 使用成功、错误和完成与 .done()、.fail() 和 always()

如何设置缓存:jQuery.get 调用中的 false

如何在jQuery中 Select 具有特定ID的所有元素?

如何使用给定的 url 判断图像是否存在?

如何禁用在div内单击

如何将参数传递给 JavaScript 中的匿名函数?

Jquery .show() 不显示隐藏可见性的 div

循环判断复选框并计算每个选中或未选中的复选框

如何使用 Twitter Bootstrap 自动关闭alert

$(document).on("click"... 不工作?

更改 Eclipse 设置以忽略特定文件上的错误

JavaScript 等效于 jQuery 的扩展方法

为什么要定义一个匿名函数并将 jQuery 作为参数传递给它?

如何复制 pinterest.com 的绝对 div 堆叠布局

Ajax 处理中的无效 JSON 原语

如何使用 JQuery 删除onclick?