Javascript:
function submitComment(e){
e.preventDefault();
var comment = $('#????').val(); // how do I get the ID?
// ajax
}
评论表:
<form id="comment-form[id]" onsubmit="submitComment(event)">
<input id="comment-input[id]" type="text" placeholder="Comment...">
</form>
[id]
是特定表单的变量ID。它有 ID 的原因是因为我有一个 for 循环来显示整个帖子列表,并且每个帖子都有自己的评论表单(想想 Facebook)。
我想知道的是,如何根据提交的表单的ID获取评论输入框提交时的值(文本)。
最佳答案
您可以使用event.target
。
var comment = $('input[id^="comment-input"]',e.target).val()
这将为您提供输入值。
e.target
将为您提供当前表单。- 然后您可以使用
[^=""]
- 以选择器开头的属性来查找输入元素。
how I can get the value (text) of the comment input box based on the ID of the form that was submitted
var formID = e.target.id; //get form ID
var comment = $('#'+formID+' input[id^="comment-input"]').val()
//use $('#parent child') selector.
关于javascript - 使用onsubmit时获取表单ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30682786/