I have a relatively simple HTML / JavaScript form. Such as this:
<form method='POST' action='someurl'>
<label for='field1'>Your name</label>
<input id='field1' name='field1' type='text' />
<label for='field2'>Status</label>
<select id='field2' name='field2'>
<option>-select one-</option>
<option value='Employee'>Employee</option>
<option value='Retiree'>Retiree</option>
</select>
<label for='field3'>City you work in</label>
<input id='field3' name='field3' type='text' />
</form>
What I need to be able to do, is change the text inside of the label for field3 based on the selected value in field2. So when field2 has ‘Employee’ selected the field3 label says ‘City you work in’, but when field2 has ‘Retiree’ selected then field3’s label should be ‘City where you live’.
One solution I have done is to have multiple tags inside of the field3 label, and then using some JavaScript I can toggle which of the tags inside the label is being displayed, like this:
// Form as above
<label for='field3'>
<span id='field3EmployeeLabel' style='display:none;'>City you work in</span>
<span id='field3RetireeLabel' style='display:none;'>City where you live</span>
</label>
<input id='field3' name='field3' type='text' />
function updateLabel() {
if($('#field2').val()=='Employee') {
$('#field3RetireeLabel').hide();
$('#field3EmployeeLabel').show();
}
else if($('#field2').val()=='Retiree') {
$('#field3EmployeeLabel').hide();
$('#field3RetireeLabel').show();
}
else {
$('#field3RetireeLabel').hide();
$('#field3EmployeeLabel').show();
}
}
The main reason that I don’t like this is that it all has to be coded by hand, and this is just a simple example, what if there are 7 or 8 different options in field2? Also, what if I had to combine multiple form field values to figure out which label to display?
Is there a design pattern or best-practice for this sort of thing in HTML? How have others handled this sort of requirement on their forms?
Create a map of values to labels to display http://jsfiddle.net/mendesjuan/VBVtE/3/ When you add new options, just add them to the labels map.
JS