jQuery Validate插件,在表单有效时启用提交按钮而不需要急切验证

时间:2015-09-28 07:51:25

标签: jquery

在我的情况下,我有各种元素,如输入,选择,复选框,收音机。有没有办法找出表单是否有效并启用提交按钮。目前我正在做的是,调用.valid()方法来查找表单的有效性,这会触发元素验证并在我点击任何我想要避免的元素时显示错误消息。

1 个答案:

答案 0 :(得分:2)

您在寻找这样的解决方案:

$(document).ready(function(){
  
  $("input.submit").prop("disabled", true);
  
  $('form').validate({
	showErrors: function(errorMap, errorList) {

		var formSelector = '#' + this.currentForm.id;
		var formObject = $(formSelector);
		var validateObject = formObject.validate();
		var numberOfInvalids = validateObject.numberOfInvalids();

		if(numberOfInvalids == 0)
		$("input.submit").prop("disabled", false);
		else
		$("input.submit").prop("disabled", true);
      
    }
 });
    
 $("#commentForm").valid();
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<form class="cmxform" id="commentForm" method="get" action="">
	<fieldset>
	<legend>Please provide your name, email address (won't be published) and a comment</legend>
	<p>
	<label for="cname">Name (required, at least 2 characters)</label>
	<input id="cname" name="name" minlength="2" type="text" required>
	</p>
	<p>
	<label for="cemail">E-Mail (required)</label>
	<input id="cemail" type="email" name="email" required>
	</p>
	<p>
	<label for="curl">URL (optional)</label>
	<input id="curl" type="url" name="url">
	</p>
	<p>
	<label for="ccomment">Your comment (required)</label>
	<textarea id="ccomment" name="comment" required></textarea>
	</p>
	<p>
	<input class="submit" type="submit" value="Submit" >
	</p>
	</fieldset>
</form>