Wednesday, January 19

Physical Address same as Mailing

This project has a need to know your physical location, but might need to mail you something too. Sometimes these are not the same, so we make input boxes for both. In most cases, they are the same, so we create a check box that says "Same as physical address." When they check it, the second set of address inputs are automatically filled and disabled.

So we start with a simple form.

<strong>Physical Address</strong>
<label for="pstr">Street *</label><input type="text" name="pstr" id="pstr" />
<label for="pstr2">Street 2</label><input type="text" name="pstr2" id="pstr2" />
<label for="pzip">Zip *</label><input type="text" name="pzip" id="pzip" />
<strong>Mailing Address</strong>
<label for="same">Same as Physical Address</label><input type="checkbox" name="same" id="same" value="same" />
<label for="mstr">Street *</label><input type="text" name="mstr" id="mstr" />
<label for="mstr2">Steet 2</label><input type="text" name="mstr2" id="mstr2" />
<label for="mzip">Zip *</label><input type="text" name="mzip" id="mzip" />

The jQuery has to not only populate and disable the fields when the box is checked, it has to make sure the validation passes. Then if someone changes their mind and unchecks the box, it has to un disable the boxes and clear them out.
$(document).ready(function(){
$('input:checkbox[name=same]').change(function(){
if($(this).is(':checked')){
$('#mstr').val($('#pstr').val());
$('#mstr2').val($('#pstr2').val());
$('#mzip').val($('#pzip').val());
$('#mstr').attr('disabled', 'disabled');
$('#mstr2').attr('disabled', 'disabled');
$('#mzip').attr('disabled', 'disabled');
$('#mstr').removeClass('error');
$('#mstr2').removeClass('error');
$('#mzip').removeClass('error');
}else{
$('#mstr').removeAttr('disabled');
$('#mstr2').removeAttr('disabled');
$('#mzip').removeAttr('disabled');
$('#mstr').removeAttr('value');
$('#mstr2').removeAttr('value');
$('#mzip').removeAttr('value');
}
});
});

And with some formatting, it looks like this.