我在使用jquery验证插件(http://jqueryvalidation.org)和jquery ui对话框时遇到了问题。 我在这里读到:jQuery UI Dialog validation without using <form> tags 但建议的仍然不起作用。
下面是我的jQuery:
$( '#addModal' ).dialog({
autoOpen: false,
modal: true,
buttons: {
'Create': function() {
$( '#addForm' ).validate({
rules: {
titleAdd: { required: true },
descriptionAdd: { required: true }
},
submitHandler: function( form ) {
$( this ).dialog( 'close' );
// ... AJAX call
} //end submitHandler
}); //end validate()
},
Cancel: function() {
$( this ).dialog( 'close' );
}
} //end buttons
}); //end Create Form Modal
下面是HTML:
<div id="addModal" title="Add new Appointment">
<form name="addForm" id="addForm" action="" method="POST" accept-charset="utf-8">
<div class="row">
<div class="form-group col-md-12">
<label for="title">Appointment Title</label>
<input type="text" id="titleAdd" class="form-control" name="title" />
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="description">Description</label>
<textarea id="descriptionAdd" name="description" cols="20" rows="4" class="form-control"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-2">
<input type="submit" name="save" value="Save" class="form-control btn btn-default btn-primary" tabindex="-1" style="position:absolute; top:-1000px">
</div>
</div>
<input type="hidden" id="id" name="id" />
</form>
我甚至尝试过建议:https://stackoverflow.com/a/2142126
甚至这个: https://stackoverflow.com/a/7390327 还试过这个:https://stackoverflow.com/a/18721278 仍然不起作用。
答案 0 :(得分:7)
我似乎解决了自己的问题。
我将validate()移到对话框之外并更改了规则。
我之前使用id
作为规则,从来不知道它应该是input name
$('#addForm').validate({
rules: {
title: { required: true },
description: { required: true }
}
});
$( '#addModal' ).dialog({
autoOpen: false,
modal: true,
buttons: {
'Create': function() {
if ( $( '#addForm' ).valid() ) {
$( this ).dialog( 'close' );
// ... AJAX call
} //end if
},
Cancel: function() {
$( this ).dialog( 'close' );
}
} //end buttons
}); //end Create Form Modal