jQuery在提交后删除输入文本
我在聊天中加入了jQuery脚本,这样消息发送时就不会刷新页面jQuery在提交后删除输入文本,jquery,jquery-validate,Jquery,Jquery Validate,我在聊天中加入了jQuery脚本,这样消息发送时就不会刷新页面 <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> $(文档).ready(函数(){ $(“#msgsend”).validate({ 类型:“POST”, 调试:错误, submitHandler:函数(表单){ //为有效的表单做其他事情 $.post('index.p
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
$(文档).ready(函数(){
$(“#msgsend”).validate({
类型:“POST”,
调试:错误,
submitHandler:函数(表单){
//为有效的表单做其他事情
$.post('index.php',$(“#msgsend”).serialize(),函数(数据){
});
}
});
});
和形式
<form id="msgsending" name="form" method="post" action="" >
<input name="message" id="message" type="text" maxlength="350" />
<input name="message" id="message" type="text" maxlength="350" />
<input name="submit" type="submit" value="Send!" />
</form>
代码工作得很好。(索引是在数据库中插入消息+用户名的脚本)
但现在我有一个问题
提交后不删除消息输入上的文本。
我用谷歌搜索了很多网页,但所有的代码都不起作用。(某些已工作,但消息未发送)
你对我有什么建议?$('message').val(''
应该清除输入的值,我猜在消息发送后您会这样做,比如:
$(document).ready(function(){
$("#msgsending").validate({
type: "POST",
debug: false,
submitHandler: function(form) {
// do other stuff for a valid form
$.post('index.php', $("#msgsending").serialize(), function(data) {
$('#message').val('');
});
}
});
});
var data = $("#msgsending").serialize();
$('#message').val('');
$.post('index.php', data, function(data) {
});
这只适用于具有ID
#消息的第一个元素,因为ID
是唯一的,不能有两个具有相同ID
的元素而不是
$.post('index.php', $("#msgsending").serialize(), function(data) {
});
你可以这样做:
$(document).ready(function(){
$("#msgsending").validate({
type: "POST",
debug: false,
submitHandler: function(form) {
// do other stuff for a valid form
$.post('index.php', $("#msgsending").serialize(), function(data) {
$('#message').val('');
});
}
});
});
var data = $("#msgsending").serialize();
$('#message').val('');
$.post('index.php', data, function(data) {
});
要在发送请求之前或按照@adeneo的建议清空消息字段,您可以在AJAX的成功回调中清空该字段。您可以在.post()
的回调函数中放置任何代码以清除或重置表单
您还可以将键入:“POST”
列为.validate()
的一个选项。你应该移除这个,因为它是
由于您使用的是ajax,因此需要在submitHandler
末尾使用return false
,以防止页面重定向
您还可以选择将$(“#msgsend”).serialize()
替换为$(form).serialize()
或form.serialize()
,因为form
被传递到submitHandler
回调函数中
$(document).ready(function(){
$("#msgsending").validate({
type: "POST", // <-- REMOVE THIS... not a valid plugin option
debug: false,
submitHandler: function(form) {
// do other stuff for a valid form
$.post('index.php', $(form).serialize(), function(data) {
$('#message').val(''); // clears out #message
// any other code to clear out or reset the form
});
return false; // prevent page redirection
}
});
});
$(文档).ready(函数(){
$(“#msgsend”).validate({
键入:“POST”//您在两个输入上使用了id=message
。jQuery假设只有一个元素具有该id,并且它只访问第一个元素。实际上,我只使用了一个。但在编写问题时,我不小心放了两个。谢谢!我是jQuery的初学者,我没有想过这样做。