What I want to do is, when a user lands on the form. I want the first input to be active, so the user is able to click in, select or fill it out. I want them to fill out the form step by step so I want the next input only to activate once they have filled out the current input.
I also want the submit button to be deactivated and not to be activated until all the inputs are filled out.
What's the best way of achieving this?
I have attached an image to illustrate what I'm trying to do.
This might give you a nice starting point: Fiddle
Add a step
class to each of your form elements (I do believe for this to work they need to be each other's siblings):
<form class="step-by-step">
<!-- Start with only the first one enabled -->
<input type="text" class="step" id="step1" />
<input type="text" class="step" id="step2" disabled />
<input type="text" class="step" id="step3" disabled />
<!-- Also works with selects,
as long as you keep track of IDs -->
<select id="step4" class="step" disabled>
<option value="">Choose one</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="step5" class="step" disabled>
<option value="">Choose one</option>
<option value="europe">Europe</option>
<option value="america">America</option>
</select>
</form>
Then, use the next()
function to find the next step in the form when something changes, and either disable or enable it (or all next steps, if the element was empty):
// The change event is fired when a form element loses focus
// and its value has changed since the last time we interacted with it
$('.step').change(function() {
var next_step = $(this).next('.step');
var all_next_steps = $(this).nextAll('.step');
// If the element *has* a value
if ($(this).val()) {
// Should also perform validation here
next_step.attr('disabled', false);
}
// If the element doesn't have a value
else {
// Clear the value of all next steps and disable
all_next_steps.val('');
all_next_steps.attr('disabled', true);
}
});
For TAB functionality, the following is a quick fix, which I'm sure can be somehow integrated with the above function.
$('.step').keydown(function(event) {
// If they pressed tab AND the input has a (valid) value
if ($(this).val() && event.keyCode == 9) {
$(this).next('.step').attr('disabled', false);
}
});
Few things to consider:
Forms can be submitted by either clicking a button with a type="submit" or by a return key.
So, in order for you to achieve the desired effect:
- $("form").find("input:first").focus(); // To autofocus the first input field.
- Make sure all inputs have a "tabindex" attribute so user can cycle using tab.
- Javascript must disable the form action until the user passes the validation.