I have a drop-down selector and form fields below. I need to be able to display form labels and corresponding form fields based on selected option.
What is the best way to implement this: prepare possible labels and fields and forms elements and store them in hidden divs and then show/hide based on selection?
<script type="text/javascript">
$(function() {
$('#mySelector').change(function(){
$('.opt').hide();
$('#' + $(this).val()).toggle();
});
});
</script>
<select id="mySelector">
<option value="o1">Car details
<option value="o2">Boat details
<option value="o3">Train details
</select>
<div id="o1" class="opt">
<label for="f1_1">Car speed</label>
<input id="f1_1" type="text">
<br>
<label for="f1_2">Car color</label>
<input id="f1_2" type="text">
</div>
<div id="o2" class="opt">
<label for="f2_1">Boat size</label>
<input id="f2_1" type="text">
<br>
<label for="f2_2">Boat weight</label>
<input id="f2_2" type="text">
</div>
<div id="o3" class="opt">
<label for="f3_1">Train length</label>
<input id="f3_1" type="text">
<br>
<label for="f3_2">Train cargo</label>
<input id="f3_2" type="text">
</div>
I assume jQuery is the best way to go…
Also, I will display this 3 times, once for each option. I need some sort of mechanist to prevent selecting the same option that has been selected above. Is it possible?
If the ‘weight’ of these elements is light then putting them in your page and dynamically toggling which is visible is not a bad idea. Otherwise, you probably should fetch the content via ajax.
I would probably add a class (maybe ‘info’ to each of the divs). That way you can use
to initially hide the elements and
If you need to use ajax, you probably will need a placeholder div…
and use
to dynamically fetch the html.
Hope this gets you started.
Bob