I have a form which is going to contain 4 fieldsets. The user must fill in a minimum of 1 fieldset but can choose to complete additional fieldsets. Each fieldset’s contents are identical.
I want them to be able to choose a number of fieldsets to show from a dropdown. On selecting a number from the dropdown the relevant number of fieldsets appears.
So if they choose 3 from the quantity dropdown, the first 3 fieldsets should be shown. If they change their mind and drop to 2 fieldsets then the 3rd should hide again.
Here’s the base HTML.
<form>
<select id="quantity" name="quantity">
<option disabled="disabled">xx</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<fieldset id="fieldset_name_1">Form Area 1</fieldset>
<fieldset id="fieldset_name_2" style="display: none;">Form Area 2</fieldset>
<fieldset id="fieldset_name_3" style="display: none;">Form Area 3</fieldset>
<fieldset id="fieldset_name_4" style="display: none;">Form Area 4</fieldset>
</form>
And here’s my very basic jQuery so far. I’m quite a noob to client side stuff, generally burying my head in php 🙂
var registerCount = function() {
var qty = $(this).val();
var fieldsets = $('fieldset');
fieldsets.slice(0, qty ).show();
}
$("#quantity").change(registerCount).keypress(registerCount);
So I’ve got it showing fieldsets correctly, I’m just not sure how to hide them on change or keypress again.
I’m sure this is simple but I think my familiarity with PHP keeps me trying to code things completely differently to the jQuery/javascript way.
To hide the unselected, you hide all before showing the selected: