我想驗證以動態方式創建的表單中的元素。但是,在下面的代碼中添加規則('$("#email"+index).rules("add", { required:true,email:true });'
)的代碼似乎不起作用(例如,沒有響應)。向動態添加的元素添加驗證規則
我在做什麼錯? (對於這個添加規則代碼,我使用了page view-source:http://www.coldfusionjedi.com/demos/jqueryvalidation/testadd.cfm作爲例子,它可以工作,還在document.ready函數的開始處添加了.validate(),例如在添加jQuery - How to dynamically add a validation rule中建議的規則之前,
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js" ></script>
<script type="text/javascript" src="/jquery/jquery.validate.js"></script>
<script type="text/javascript" src="js/additional-methods-v2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var wrapper = $("#wrapper");
var addForm = $("#add-form");
var index = 0;
$("#myForm").validate();
var getForm = function(index, action) { //returns set of form fields as a string
return $('\
<table>\
<tr>\
<td> Name </td> <td> Email </td> <td> Phone </td>\
</tr>\
<tr>\
<td> <input id="name' + index + '" name="name' + index + '" /></td>\
<td><input id="email' + index + '" name="email' + index + '" /></td>\
<td><input id="phone' + index + '" name="phone' + index + '" /></td>\
<input type="submit" value="Save">\
</tr>\
</table>\
<a href="#" class="remove">remove form</a>\
');
}//getForm()
addForm.on("click", function() {
var form = getForm(++index)
form.find(".remove").on("click", function() {
$(this).parent().remove();
}); //form.find()
$("#wrapper").append(form);
$("#email"+index).rules("add", { required:true,email:true });
}); //addForm.on()
$("#myForm").validate({
//console.log("validate");
errorPlacement: function(error, element) {
error.insertAfter(element);
},
rules: {
email: {
required: true
}
} //rules
}); //validate()
}); //$(document).ready
</script>
</head>
<body>
<form id="myForm" name="myForm" action="" method="post" autocomplete="on">
<div id="wrapper"></div>
<a href="#" id="add-form">add form</a>
</form>
</body>
</html>
這之前http://stackoverflow.com/questions/3033910/jquery-被問如何動態地添加驗證規則 –
正確,我也參考了該鏈接,並指出在添加規則之前添加.validate()似乎不起作用;我添加了'$(「#myForm」)。validate();' ('#email'+ index).rules(「add」,{required:true,email:true});''並且通過將驗證行置於文檔就緒功能的開始嘗試。我也可以問:在代碼中放置$(「#myForm」).validate()行的位置(如果這將是錯誤)? – Joppo