I’m creating a php Contact Form for a friend’s bike courier service. Basically, when the “shipping and billing address is the same” box is checked, I want the two sets of fields to be in sync after every keyup event.
The form is pretty straight forward:
<!-- Get the shipping address inputs -->
<input type="text" name="company_address1" value="" id="company_address1">
<input type="text" name="company_city" value="" id="company_city">
<!-- Get the billing address inputs -->
<p>Same as above <input type="checkbox" name="dupe" id="dupe" value=""></p>
<input type="text" name="billing_address1" value="" id="billing_address1">
<input type="text" name="billing_city" value="" id="billing_city">
The jQuery
$("input#dupe").click(function(){
if ($("input#dupe").is(':checked'))
{
// Checked, copy values
$("input#billing_address1").val($("input#company_address1").val());
$("input#billing_city").val($("input#company_city").val());
}
else
{
// Clear on uncheck
$("input#billing_address1").val("");
$("input#billing_city").val("");
}
});
$("input#company_address1").keyup(function(event) {
if ($("input#dupe").is(':checked')) {
var stt=$(this).val();
$("input#billing_address1").val(stt);
}
});
$("input#company_city").keyup(function(event) {
if ($("input#dupe").is(':checked')) {
var stt=$(this).val();
$("input#billing_city").val(stt);
}
});
$("input#billing_address1").keyup(function(event) {
if ($("input#dupe").is(':checked')) {
var stt=$(this).val();
$("input#company_address1").val(stt);
}
});
$("input#billing_city").keyup(function(event) {
if ($("input#dupe").is(':checked')) {
var stt=$(this).val();
$("input#company_city").val(stt);
}
});
Optimization is not one of my strong points, is there a way I can chain the events together?
You could have jQuery simply disable the second set of fields when the checkbox is ticked, and then look at the value of the checkbox on the server end when the form is submitted.
If you want to keep the design you have, probably look at writing a single keyup() function for all fields in the input form; extract the id of the element that triggered the function; edit the id a little (replace ‘billing’ with ‘company’, etc), and then do the $(“…”).val () bit.