问题
I am using jQuery form validation plugin and I need to display an error when a user clicks a submit button while the form is empty. However, my click event is not responsive.
<!DOCTYPE HTML>
<html>
<head>
<link type = "text/css" rel="stylesheet" href="css/bootstrap.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery- validation/jquery.validate.js"></script>
<script src="js/bootstrap.js"> </script>
<script>
$('#submit').click(function(){
$('form').validate()
});
</script>
</head>
<body>
<form class = "well span6">
<label> Username </label>
<input type="text" id = "myName" class ="span3" placeholder ="Type your username here..." class = "required"/>
<label> Password</label>
<input type="text" id "myPassword" class ="span3" placeholder ="Type your password here..." class = "required"/> <br/>
<button id = "submit" class ="btn btn-primary">Submit </button>
<button class = "" > Clear <br/></button><br/>
</form>
</body>
</html>
Any help will be appreciated and rewarded.
回答1:
When you bind .validate() to a click or submit event, you are only first initializing the plugin on the first click. Since validation plugin was not ready when you first clicked the button, nothing happens or it behaves unexpectedly.
As already pointed out, you simply need to initialize the plugin on DOM ready. The plugin already has event handlers built in that take care of validating the form automatically on various events, including the submit click.
$(document).ready(function() {
$('form').validate();
});
You also had two class attributes on your input elements which was causing the required class to be ignored.
<input type="text" id="myName" class="span3" placeholder="Type your username here..." class="required" />
Simply combine them:
<input type="text" name="myName" id="myName" class="span3 required" placeholder="Type your username here..." />
I also added the name attribute to each input element.
Working Demo:
http://jsfiddle.net/ZjVWd/
回答2:
Just attach validation to the form when the document is ready, it automatically validates when the user tries to submit:
$(function () {
$("form").validate();
});
The validate() function does not actually perform validation, it just initializes the plugin and attaches it to the specified form. If you want to perform on-demand validation, you can call valid() after having initialized it. But you don't need to do this if you just want validation done automatically during submission, that's the default behavior of the plugin.
来源:https://stackoverflow.com/questions/14106825/button-click-event-non-responsive