Using jQuery Validate to check sections of a form at a time
I'm trying to figure out how to incorporate jquery validate into my questionaire form. The form itself is broken up into sections (divs) that are hidden and slide up and down using jquery. This way I can stuff a large form into a single page for various reasons and still keep it clean(ish). The problem is I cannot figure out how to incorporate jquery into the form in such a way that I validate only sections, or certain fields at a time, before toggling to the next section.
Here is some very basic code illustrating the form
<script>
$(document).ready(function(){
$(".go_section2").click(function(){
// need to validate section 1 fields here or stop section jump
$("#section2").slideDown("slow");
});
$(".go_section3").click(function(){
// need to validate section 3 fields here or stop section jump
$("#section3").slideDown("slow");
});
// etc...
});
</script>
<form name="theForm" id="theForm" class="theForm" method="POST" action="">
<!-- Section 1 -->
<div class="questionnaireHeader">Section 1 Header</div>
<div id="section1" class="questionnaireSection">
<label for="FirstName">First Name</label>
<input id="FirstName" name="FirstName"/><br />
<label for="LastName">Last Name</label>
<input id="LastName" name="LastName"/><br />
[form fields for section 1]<br />
<span class="go_section2">next</span>
</div>
<!-- Section 2 -->
<div class="questionnaireHeader">Section 2 Header</div>
<div id="section2" class="questionnaireSection" style="display:none;">
[form fields for section 2]
</div>
<!-- Section 3 thru x -->
</form>
So what should happen is when a user clicks on 'next' in section 1 it will validate that both firstname and lastname have values.. (the rules themselves I should be able to setup) and then perform the toggle. If any fields are not valid I would like the input /filled in red or some such effect. 开发者_Python百科If everything validates then it continues on and displays the next section which itself will validate only it's own section and so on and so on.
I appreciate any help that can be provided, I've been pouring through examples and haven't been able to make anything work yet.
use this:
$(".go_section2").click(function(){
if($(this).find('input:text').val()!==""&&$(this).find('input:text').val()!==null){
$("#section2").slideDown("slow");
}
else{
$(this).find('input:text').css('border','1px solid red');
}
});
and make sure you add type="text"
to your text inputs
Ended up using something along these lines I found on the jQuery Forums
$("#buttonNext").click(function(){
//apply/remove ignore rules here
if $("form").valid()
//hide current step and display next step
return false; // do not submit
});
//On your submit button
$("#submitButton").click(function(){
// remove all ignore if required
$("form").submit();
});
精彩评论