Kei*_*gan 4 forms validation ajax jquery
我有一个简单的电子邮件地址注册表格如下:
<form action="" id="newsletterform" method="get">
<input type="text" name="email" class="required email" id="textnewsletter" />
<input type="submit" id="signup" />
</form>
Run Code Online (Sandbox Code Playgroud)
这是我希望能够做到的:
我看过太多的教程,在这个阶段我的眼睛非常疼,所以请不要指向任何网址(我很可能已经在那里).
如果有人可以提供一个关于做什么的准系统,那将非常感激.
首先,请确保您在服务器端进行所有验证.我喜欢让我的表单在没有任何JavaScript的情况下工作.我假设你已经做了那么多.
****原始答案***
然后,将"submit"元素更改为按钮元素.在按钮元素的OnClick上,运行验证的JavaScript函数.如你所知,有很多关于如何做到这一点的样本.
如果验证失败,请发送警报.如果成功,请使用JavaScript提交表单.
****新,工具使用答案***
你也可以使用JQuery(orip指出)和它的插件来做到这一点.他们处理了很多艰苦的工作.请确保我的评论正在讲述正确的故事.这段代码也提交了AJAX.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- Load JQuery on your page -->
<script src="http://code.jquery.com/jquery-latest.js"></script>
<!-- Load JQuery validation sytles and (rules?) on your page -->
<link rel="stylesheet" href="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.css" type="text/css" media="screen" />
<!-- Load JQuery validation plugin on your page -->
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<!-- Load JQuery form plugin on your page -->
<script type="text/javascript" src="http://jqueryjs.googlecode.com/svn/trunk/plugins/form/jquery.form.js"></script>
<script type="text/javascript" language="javascript">
//Wait until the document is loaded, then call the validation. Due to magic in JQuery or the plugin
// this only happens when the form is submitted.
$(document).ready(function(){
//When the submit button is clicked
$("#signup").click(function() {
//if the form is valid according to the fules
if ($("#newsletterform").valid()) {
//Submit the form via AJAX
$('#newsletterform').ajaxForm(function() {
//this alert lets me know the submission was successfull
alert("Thank you!"); });
}
})
});
</script>
<!-- Just some styles -->
<style type="text/css">
* { font-family: Verdana; font-size: 96%; }
label { width: 10em; float: left; }
label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
p { clear: both; }
.submit { margin-left: 12em; }
em { font-weight: bold; padding-right: 1em; vertical-align: top; }
</style>
</head>
<body>
<form action="" id="newsletterform" method="get">
<!-- The classes assigned here are where the validation rules come fome.
This is required, and it must be an email -->
<input type="text" name="email" class="required email" id="textnewsletter" />
<input type="submit" id="signup" />
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这不是你能写的最严密的代码,但它将作为一个例子.
| 归档时间: |
|
| 查看次数: |
6936 次 |
| 最近记录: |