gpt4 book ai didi

javascript - 使用onsubmit时获取表单ID

转载 作者:行者123 更新时间:2023-12-02 16:06:15 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com