我的网站上有多个具有相同输入名称的表单,因此我使用dataString = $(this).parent().serialize();
。
脚本本身运行正常,但我不想附加特定输入字段中的文本。
AJAX:
$(document).ready(function(){
$('.AnswerPQSubmit').click(function() {
dataString = $(this).parent().serialize();
var pqid = $(".pqid").val();
var answerpq = $(".answerpq").val();
$.ajax({
type: 'post',
url: 'postpqanswer.php',
data: dataString,
dataType: 'html',
success: function(data) {
$(".comment"+pqid).append('<p>'+answerpq'</p>');
}
});
return false;
});
});
HTML:
<form method="post">
<input type="text" name="answerpq" class="answerpq" placeholder="Write your answer" />
<input type="hidden" name="pqid" class="pqid" value="<?php echo $rowA['pq_id']; ?>" />
<input type="submit" name="AnswerPQSubmit" class="AnswerPQSubmit" value="Send" />
<span class="comment<?php echo $rowA['pq_id']; ?>"></span>
</form>
我试图做的是通过在“评论”末尾添加帖子的ID来给“评论范围”一个独特的类。
所以......我正在尝试将特定输入的文本追加到评论 id 。它有点工作,但因为我使用了这个:dataString = $(this).parent().serialize();
这个var var pqid = $(".pqid").val();
只是在文档中找到第一个pgid类,而不是$this
形式的那个。
我正在寻找的是这样的:
var pqid = $(this).(".pqid").val();
我知道这条线无效。但是这可以让你了解我在寻找什么。我现在迷路了。
答案 0 :(得分:1)
您的实现问题是$(".pqid").val()
将始终返回第一个元素的值。您可以使用.siblings()
来定位兄弟元素。
var pqid = $(this).siblings(".pqid").val();
var answerpq= $(this).siblings(".answerpq").val();
但我建议你绑定submit
个事件而不是click
。
HTML 的
<form class="PQSubmit" method="post">
<input type="text" name="answerpq" class="answerpq" placeholder="Write your answer" />
<input type="hidden" name="pqid" class="pqid" value="<?php echo $rowA['pq_id']; ?>" />
<input type="submit" name="AnswerPQSubmit" class="AnswerPQSubmit" value="Send" />
<span class="comment comment<?php echo $rowA['pq_id']; ?>"></span>
</form>
脚本
$(document).ready(function(){
$('.PQSubmit').submit(function(event) {
event.preventDefault(); //cancel default action
dataString = $(this).serialize();
var pqid = $(this).find(".pqid").val();
var answerpq = $(this).find(".answerpq").val();
var commentSection = $(this).find(".comment")
$.ajax({
type: 'post',
url: 'postpqanswer.php',
data: dataString,
dataType: 'html',
success: function(data) {
commentSection.append('<p>'+answerpq'</p>');
}
});
return false;
});
});
答案 1 :(得分:1)
您可以通过以下方式获取当前输入值:
var pqid = $(this).parent("form").find(".pqid").val();
答案 2 :(得分:0)
var pqid = $(".pqid").val();
var answerpq = $(".answerpq").val();
将上述两行移至ajax成功范围内以获取最新值。
$(document).ready(function(){
$('.AnswerPQSubmit').click(function() {
dataString = $(this).parent().serialize();
$.ajax({
type: 'post',
url: 'postpqanswer.php',
data: dataString,
dataType: 'html',
success: function(data) {
var pqid = $(".pqid").val();
var answerpq = $(".answerpq").val();
$(".comment"+pqid).append('<p>'+answerpq'</p>');
}
});
return false;
});
});