What is the most efficient way of showing/hiding form fields based on the value of a select control? I have one select control and three input fields, which show/hide based
Few things:
1) I would add a class (I used .additional-field below) to each of the additional fields. This will allow you to hide them all in one swoop instead of requiring you to $.hide()
each one explicitly. It's not so bad with just three, but if you ended up with much more, it'd get hairy quick.
2) I put the code in a function and both call that function on page load and use it as the parameter to .change()
. This saves repeating the same code, and covers the case of an initial value from either editing an existing one or an error in the form that needs to be corrected. Otherwise, the additional field wouldn't show until you chose something else and then chose the item again.
$(document).ready(function(){
function toggleBusinessTypeAdditionalFields() {
$('.additional-field').hide();
var selected = $('#business-type').val();
switch (selected) {
case 1:
$('#soletrader').show();
break;
case 3:
$('#publicsector').show();
break;
case 5:
$('#charity').show();
break;
}
}
toggleBusinessTypeAdditionalFields();
$('#business-type').change(toggleBusinessTypeAdditionalFields);
});