使用 JQuery 获取 TextArea
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9548144/
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
Getting TextArea Using JQuery
提问by Devin Dixon
I am submitting a form using JQuery. The form looks like below
我正在使用 JQuery 提交表单。表格如下所示
<form class="ask-more-form">
<div class="product_info_2">
<textarea name="product_question" class="textbox" placeholder="Ask You Question Here"></textarea>
</div>
<input type="hidden" name="product_id" value="1" id="product_id">
<a href="#" class="whiteButton submit" id="ask-more-submit-button">Ask Question</a>
</form>
And the JQuery to catch the form looks like this:
捕获表单的 JQuery 如下所示:
$('#ask-more').on('submit', '.ask-more-form', function() {
var product_id = $(this).children('input[name=product_id]').val();
var product_question = $(this).children('textarea[name="product_question"]').text();
alert(product_question);
//submitQuestion(product_id, product_question);
});
The product_id is always read but the product question is is always null. Can anyone tell me why this is happening?
product_id 总是被读取,但产品问题总是为空。谁能告诉我为什么会这样?
回答by pete
.children
only goes one level down. Use .find
instead:
.children
只下降一级。使用.find
来代替:
$('#ask-more').on('submit', '.ask-more-form', function () {
var product_id = $(this).children('input[name=product_id]').val();
var product_question = $(this).find('textarea[name="product_question"]').text();
alert(product_question);
//submitQuestion(product_id, product_question);
});
回答by JaredPar
You're using text()
on a <textarea>
when you should be using val()
你在你应该使用text()
的<textarea>
时候使用val()
var product_question = $(this).children('textarea[name="product_question"]').val();
This is true for other input element types like <select>
and <input>
这适用于其他输入元素类型,例如<select>
和<input>
回答by Kunal Vashist
Use .val() instead of .text()
. It will do the trick
Use .val() instead of .text()
. 它会做的伎俩
回答by Brombomb
You don't need to use children
or find
. Since you already have the id
of the form you can use that for your base and just use a standard jquery selector like so:
您不需要使用children
或find
。由于您已经拥有id
表单的,因此您可以将其用于您的基础,并且只需使用标准的 jquery 选择器,如下所示:
var product_question = $('textarea[name="product_question"]', this).val();
by adding a seocnd argument you are telling jquery to use only this
as the DOM tree.
通过添加 seocnd 参数,您告诉 jquery 仅用this
作 DOM 树。