我有一个带有一个按钮和一个 div(newFormDiv)的 html 页面,当用户单击该按钮时,它会调用一个 ajax 函数在 div newFormDiv 中编写一个新表单(commentForm)。在新表单中,用户将在 artPlaceName 中输入一些内容,长度必须大于 1。我尝试使用 jquery 验证来做到这一点,但从未成功。
任何帮助将不胜感激。
索引.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script src="formajax.js"></script>
<script src="formvalidation.js"></script>
</head>
<body>
<form>
<button>Create New Form</button>
</form>
<div id="newFormDiv">
<p>This is new form area.</p>
</div>
<script>
$( "button" ).click(function () {
testFutureForm();
return false;
});
</script>
</body>
</html>
未来表单.php
<?php
echo '
<form id="commentForm" method="get" action="">
<fieldset>
<p>
<input id="artPlaceName" name="name" size="25"/>
</p>
<p>
<input id="placeSubmit" class="submit" type="button" value="Submit"/>
</p>
</fieldset>
</form>
';
?>
formajax.js
function testFutureForm()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 )
{
document.getElementById("newFormDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","futureForm.php",true);
xmlhttp.send();
}
表单验证.js
$( "form" ).on( "click", "#placeSubmit",
function(){$("#commentForm").validate(
{
rules:
{
artPlaceName:
{
required: true,
minlength: 2
}
},
messages:
{
artPlaceName:
{
required: "<li>Please enter a name.</li>",
minlength: "<li>Your name is not long enough.</li>"
}
}
}
);}
);