javascript - 如何在javascript中按数字序列化表单数据并使用特定数字提交
问题描述
我正在做一个个人项目,我的表格不止一个(每个帖子下的评论表格)。每个表格我都根据post id给出一个数字。
<form id="postCommentsForm<?php echo $ansRow['id'];?>" class="form">
<div class="input-group mb-3">
<a href="user/<?php echo $username;?>">
<img class="p-1 m-0" src="images/<?php echo $userAvatar;?>" width="35" height="35" alt="<?php echo $userAvatar;?> profile picture">
</a>
<input name="post_comment<?php echo $ansRow['id'];?>" id="add_comments" type="text" autofocus autocomplete="off" class="add_comments form-control pl-3 pr-3" placeholder="<?php echo $userFname;?>, type something" aria-label="Recipient's username" aria-describedby="button-form">
<input type="text" hidden id="question_id" name="question_id" value="<?php echo $row['id'];?>">
<input type="text" hidden id="answer_id" name="answer_id" value="<?php echo $ansRow['id'];?>">
<input type="text" hidden id="session_id" name="session_id" value="<?php echo $_SESSION['id'];?>">
<div class="input-group-append">
<button class="btn btn-secondary submit-comments" type="submit" name="submit_comment<?php echo $ansRow['id'];?>" id="postComments">Comment</button>
</div>
</div>
</form>
javascript代码
$(document).ready(function() {
$("[id^=postCommentsForm]").on("submit", function(e) {
e.preventDefault();
var add_comments = $("#add_comments").val();
var question_id = $("#question_id").val();
var answer_id = $("#answer_id").val();
// var session_id = $("#session_id").val();
if(add_comments == "" ){
$("#error-message").html("All fields are required!").slideDown();
$("#success-message").slideUp();
}else{
//Ajax
$.ajax({
url: "include/forms-data/comments.php",
type: "POST",
data: {
add_comments: add_comments,
question_id: question_id,
answer_id: answer_id
},
success: function(data) {
if (data != 0) {
$("[id^=postCommentsForm").trigger("reset");
$("#success-message").html("Question Added Successfully!").slideDown();
$("#error-message").slideUp();
} else {
//alert("Can't save record");
$("#error-message").html("Something went wrong!").slideDown();
$("#success-message").slideUp();
}
}
});
}
});
});
如何获取#comments(postID here),并在 postID 下成功提交表单数据?
我希望我能很好地定义这个问题。
解决方案
Jquery 的“以选择器开头”可以提供帮助。在这里查看
$(document).ready(function() {
$("[id^=comments]").click(function(e) {
var element_id = this.getAttribute("id");
});
});
现场演示:
$(document).ready(function() {
$("[id^=comments]").click(function(e) {
console.log($(this).attr('id'));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='comments1'>b</button>
<button id='comments2'>a</button>
推荐阅读
- sql - 返回带有 Null 的表时出现问题
- actions-on-google - 从网站深层链接到 Google 上的操作
- python - 如何在 x 轴上仅显示可用值
- php - 将 hex/hsl 值映射到颜色范围
- azure-devops - 在矩阵构建中使用 Build.ArtifactStagingDirectory 和 PublishPipelineArtifact
- android - 片段中的空参数捆绑
- javascript - javascript/typescript 中的代码缩减/可重用性技术
- java - 将对象列表转换为地图
> - c - 当我的角色是“*”或“/”时,这个循环不应该停止吗?
- php - 发布与页面链接 php 冲突的蛞蝓