Get value from text area [duplicate]

江枫思渺然 提交于 2019-12-17 16:24:11

问题


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

});

回答1:


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

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

Or, Here's what I would do for clean code,

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

Demo: http://jsfiddle.net/jVUsZ/




回答2:


Vanilla JS

document.getElementById("textareaID").value

jQuery

$("#textareaID").val()

Cannot do the other way round (it's always good to know what you're doing)

document.getElementById("textareaID").value() // --> TypeError: Property 'value' of object #<HTMLTextAreaElement> is not a function

jQuery:

$("#textareaID").value // --> undefined



回答3:


$('textarea').val();

textarea.value would be pure JavaScript, but here you're trying to use JavaScript as a not-valid jQuery method (.value).




回答4:


use the val() method:

$(document).ready(function () {
    var j = $("textarea");
    if (j.val().length > 0) {
        alert(j.val());
    }
});



回答5:


You need to be using .val() not .value

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



回答6:


Use val():

 if ($("textarea").val()!== "") {
        alert($("textarea").val());
    }


来源:https://stackoverflow.com/questions/14939010/get-value-from-text-area

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!