I have a simple form for a hotel accommodation tool. User selects the number of adults and children from dropdown boxes and the form then lets the user select the ages of children from newly generated dropdown boxes.
I can show and hide the select boxes. However, once a select box is shown, its value is posted no matter if it’s later hidden or not. I need to clear or reset the values of select boxes which are no longer displayed.
Here is my jquery:
$(document).ready(function(){
$("#selectchild").change(function(){
switch ($(this).val())
{
case "0":
$("#hidechild1").slideUp("fast");
$("#hidechild2").slideUp("fast");
break;
case "1":
$("#hidechild1").slideDown("fast");
$("#hidechild2").slideUp("fast");
break;
case "2":
$("#hidechild1").slideDown("fast");
$("#hidechild2").slideDown("fast");
break;
}
});
});
And here is my HTML:
<form id="ExampleForm" method="post" action="results.php">
<fieldset>
<legend>Accommodation details. Please choose number of adults and children</legend>
<div class="input select">
<label for="selectadult">Adult (>12)</label>
<select name="selectadult" id="selectadult">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div class="input select">
<label for="selectchild">Children (0-12)</label>
<select name="selectchild" id="selectchild">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div class="hide" id="hidechild1">
<br/>Please specify the ages of children:
<div class="input select">
<label for="selectchild1">Child 1:</label>
<select name="selectchild1" id="selectchild1">
<option value="none">-?-</option>
<option value="<1"><1</option>
<? for ($i=1;$i<=12;$i++) { echo "<option value=\"$i\">$i</option>"; } ?>
</select>
</div>
</div>
<div class="hide" id="hidechild2">
<div class="input select">
<label for="selectchild2">Child 2:</label>
<select name="selectchild2" id="selectchild2">
<option value="none">-?-</option>
<option value="<1"><1</option>
<? for ($i=1;$i<=12;$i++) { echo "<option value=\"$i\">$i</option>"; } ?>
</select>
</div>
</div>
</fieldset>
<div class="submit">
<input type="submit" value="Submit!" />
</div>
</form>
Try this:
This could be made prettier if you turned that function into a basic plugin, so you could call
$("#hidechild1").slideUp("fast").resetFields(), but the above will at least work for you.