Javascript 从文本区域获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14939010/
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
Get value from text area
提问by user2077469
How to get value from the textarea field when it's not equal "".
当 textarea 字段不等于“”时如何从它获取值。
I tried this code, but when I enter text into textarea the alert() isn't works. How to fix it?
我试过这段代码,但是当我在 textarea 中输入文本时,alert() 不起作用。如何解决?
<textarea name="textarea" placeholder="Enter the text..."></textarea>
$(document).ready(function () {
if ($("textarea").value !== "") {
alert($("textarea").value);
}
});
采纳答案by Muthu Kumaran
Use .val()to get value of textarea and use $.trim()to empty spaces.
使用.val()得到textarea的和使用的价值$.trim()到空的空间。
$(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);
}
});
回答by Mars Robertson
Vanilla JS
香草JS
document.getElementById("textareaID").value
jQuery
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:
jQuery:
$("#textareaID").value // --> undefined
回答by James Donnelly
$('textarea').val();
textarea.valuewould be pure JavaScript, but here you're trying to use JavaScript as a not-valid jQuery method (.value).
textarea.value将是纯 JavaScript,但在这里您试图将 JavaScript 用作无效的 jQuery 方法 ( .value)。
回答by silly
use the val() method:
使用 val() 方法:
$(document).ready(function () {
var j = $("textarea");
if (j.val().length > 0) {
alert(j.val());
}
});
回答by Sanchit
You need to be using .val()not .value
你需要使用.val()不.value
$(document).ready(function () {
if ($("textarea").val() != "") {
alert($("textarea").val());
}
});
回答by Zaheer Ahmed
Use val():
使用val():
if ($("textarea").val()!== "") {
alert($("textarea").val());
}

