Functions to optimize some redundant code
I'm using some jQuery to break up a long input form into several steps that the user navigates through using either previous/next buttons or a menu bar that has links to each of the 9 steps.
The cool thing is that after a lot of trial-and-erroring and troubleshooting, it works (I'm a rookie), but there's are pieces I'm repeating the same thing 9 times, and I'd really like some help at making it smarter. It turns out that jQuery is really awesome, so I want to get good at doing it properly.
Here's some of my code (truncated a little since you'll probably get the idea after seeing the first 4 steps instead of all 9).
First, I select each piece of the form and assign a variable to it:
- var $step1 = $('div#group-nf-household-members-items');
var $step2 = $('div#group-nf-hd-exercise-items');
var $step3 = $('div#group-nf-hd-diet-items');
var $step4 = $('fieldset.group-nf-household-waste');
Then I give each step a class:
- $step1.addClass('flux-step-1');
$step2.addClass('flux-step-2');
$step3.addClass('flux-step-3');
$step4.addClass('flux-step-4');
I use this function to show the right step:
- function showStep() {
$('[class*=flux-step-]:visible').hide();
$('.flux-step-' + currentStep).fadeIn('slow');
$('li#flux-'+currentStep).addClass('active');
}
And I use this to point the menu links to the right step:
- $('a#anchor-1').click(function() {
$('li#flux-'+currentStep).removeClass('active');
currentStep = 1;
showStep(currentStep);
});
$('a#anchor-2').click(function() {
$('li#flux-'+currentStep).removeClass('active');
currentStep = 2;
showStep(currentStep);
});
$('a#anchor-3').click(function() {
$('li#flux-'+currentStep).removeClass('active');
currentStep = 3;
showStep(currentStep);
});
$('a#anchor-4').click(function() {
$('li#flux-'+currentStep).removeClass('active');
currentStep = 4;
showStep(currentStep);
});
The part that I feel like is the worst is the code for these anchor links. Is there a way to grab the last digit of the ID on the link and then assign the currentStep variable equal to that?
How about for the part where I put the class on each step? Is there a way to use a wildcard and some sort of counting function to generate those quicker?
Thanks!