如何才能仅在提交时获取表单输入的值?我有这个..
<form id="addCommentForm<?PHP echo $PostID;?>" method="post" action="">
<input type="hidden" value="<?PHP echo $PostID;?>" name="comentonpost" id="comentonpost"/>
<textarea class="commentinput" name="body" id="body" cols="20" rows="5"></textarea>
<input type="submit" id="submit" value="Submit" />
</form>
$PostID
是一个数字,该数字在页面中打印的每个表单中都不同,因此页面上的所有表单名称都不同。在 HTML 中,它看起来像这样:
打印的第一个表格:
<form id="addCommentForm3" method="post" action="">
<input type="hidden" value="3" name="comentonpost" id="comentonpost"/>
<textarea class="commentinput" name="body" id="body" cols="20" rows="5"></textarea>
<input type="submit" id="submit" value="Submit" />
</form>
第二次打印:
<form id="addCommentForm2" method="post" action="">
<input type="hidden" value="2" name="comentonpost" id="comentonpost"/>
<textarea class="commentinput" name="body" id="body" cols="20" rows="5"></textarea>
<input type="submit" id="submit" value="Submit" />
</form>
我在 JavaScript 中获取 comentonpost
id 值,如下所示:
$(document).ready(function(){
var name_element = document.getElementById('comentonpost');
var x = name_element.value;
});
我需要这个值,以便以下脚本将新评论放在#addCommentContainer'+x
这是整个 javascript:
$(document).ready(function(){
var name_element = document.getElementById('comentonpost');
var x = name_element.value;
/* The following code is executed once the DOM is loaded */
/* This flag will prevent multiple comment submits: */
var working = false;
/* Listening for the submit event of the form: */
$('#addCommentForm'+x).submit(function(e){
e.preventDefault();
if(working) return false;
working = true;
$('#submit').val('Working..');
$('span.error').remove();
/* Sending the form fileds to submit.php: */
$.post('comment.submit.php',$(this).serialize(),function(msg){
working = false;
$('#submit').val('Submit');
/*
/ If the insert was successful, add the comment
/ below the last one on the page with a slideDown effect
/*/
$(msg.html).hide().insertBefore('#addCommentContainer'+x).slideDown();
},'json');
});
});
但通过这种方式,它会获取打印的第一个表单的值。如何仅在提交的表单上获取 comentonpost
的值?
最佳答案
当您使用 jQuery 时,您可以使用 "attribute starts with"选择器来选择表单,然后 .serialize()
或 .serializeArray()
获取整个表单数据的方法:
$('[id^="addCommentForm"]').on('submit', function (e) {
var formData;
//as string i.e. foo=bar&fizz=buzz
formData = $(this).serialize();
//as array i.e. [{name: 'foo', value: 'bar'}, {name: 'fizz', value: 'buzz'}]
formData = $(this).serializeArray();
e.preventDefault();
});
对于表单内单个字段的数据,只需选择字段并调用 .val()
:
fieldVal = $('#comentonpost').val();
也就是说,最好简单地向所有表单添加一个公共(public)类并对其进行选择:
PHP:<form class="add-comment-form" id="addCommentForm<?PHP echo $PostID;?>" method="post" action="">
JS:
$('.add-comment-form').on('submit'...
<小时/>
请注意拼写,您使用过 add<b>Comment</b>form
对于表格,但是<b>coment</b>onpost
对于该领域。
关于javascript - 如何使用javascript获取表单名称和输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16886519/