Copying Billing and Shipping Address Information with jQuery

I’m in the process of building a shopping cart for a client.  It is a custom cart that allows members of the website to post items for sale.  Think eBay without the auctions.  I’m currently building the checkout module and ran into a bit of a stumbling block - something I had build by hand in javascript many times in the past was required again - the ability for a user to click a checkbox in an HTML form and have the billing address information duplicate over to the shipping address fields on the form.

The idea itself is pretty painless, and you can find javascript examples of this functionality all over the web.  Since I am a big fan of jQuery, and learning more of it every day, I figured this would be a good opportunity to re-learn this functionality using jQuery’s modern functionality.  Well, it wasn’t quite that easy, but with some digging around on the web I found what I needed, so here is the run down.

First, let’s begin with a simple HTML form:

<form id="addressform">

<
p>Billing Address</p>
<
div id="billing_fields">
    
First: <input type="text" name="bill_firstname" value="" />
    
Last: <input type="text" name="bill_lastname" value="" />
    
Email: <input type="text" name="bill_email" value="" />
    
Country: <select id="bcountry" name="country">
        <
option value="">Select</option>
        <
option value="USA">USA</option>
        <
option value="Canada">Canada</option>
    </
select>
</
div>

<
p><input type="checkbox" id="copyaddress" /> Copy Billing Address to Shipping</p>

<
p>Shipping Address</p>
<
div id="shipping_fields">
    
First: <input type="text" name="ship_firstname" value="" />
    
Last: <input type="text" name="ship_lastname" value="" />
    
Email: <input type="text" name="ship_email" value="" />
    
Country: <select id="scountry" name="country">
        <
option value="">Select</option>
        <
option value="USA">USA</option>
        <
option value="Canada">Canada</option>
    </
select>
</
div>

</
form

Next, grab the jQuery Select Plugin from TexoTela.  So the head of your HTML page will contain this:

<script type="text/javascript" src="/path/to/jquery.js" charset="utf-8"></script>
<script type="text/javascript" src="/path/to/jquery.select.js" charset="utf-8"></script> 

And now our jQuery code, to be explained further down the page:

<script type="text/javascript">
//on page load
$(document).ready(function() {
    
    
//when the checkbox is checked or unchecked
    
$('#copyaddress').click(function() {
            
        
// If checked
        
if ($("#copyaddress").is(":checked")) {
            
            
//for each input field
            
$('#shipping_fields input'':visible'document.body).each(function(i
                
//copy the values from the billing_fields inputs
                //to the equiv inputs on the shipping_fields
                
$(this).val( $('#billing_fields input').eq(i).val() );
                
});
            
//won't work on drop downs, so get those values
            
var bcountry = $("#bcountry").val();
            $(
"#scountry").selectOptions(bcountry);                    
        
        
else {
    
            
//for each input field
            
$('#shipping_fields input'':visible'document.body).each(function(i
                
//set shipping_fields inputs to blank
                
$(this).val(""); 
                
});
            $(
"#scountry").selectOptions("");
        
}
    }
);
});
</script> 

Code Explanation

I’m hoping you don’t need any explanation on the HTML for the form, so we’ll just look at the javascript.  The following code is the basic jQuery invocation so that the script is ready to go upon page load.

<script type="text/javascript">
//on page load
$(document).ready(function() 

This code is an event handler.  It is literally read as “Run this function when the DOM element with the id ‘copyaddress’ is clicked.

//when the checkbox is checked or unchecked
$('#copyaddress').click(function() 

Evaluate the status of the “checked” attribute of the checkbox.  It reads as “If the DOM element with the id ‘copyaddress’ is checked”.

// If checked
if ($("#copyaddress").is(":checked")) 


Now we are ready to perform an action when the checkbox is clicked and the resulting click leaves it in a checked state.  That action is to grab each input element within the #shipping_fields div and do something with it.  We also want to filter out a few things.  The ‘:visible’ selector makes sure that we are only going to perform this action on elements that aren’t hidden (either by CSS, Javascript or an actual hidden input type).  The ‘document.body’ selector makes sure that we are only looking inside the body DOM element for fields to grab.  Some browsers consider other parts of the DOM as form elements, and we want to make sure we are steering clear of that.  This is kind of overkill but it doesn’t hurt much.  This reads as “Get each of the visible input fields within the document’s body and inside the #shipping_fields container.”

//for each input field
$('#shipping_fields input'':visible'document.body).each(function(i

So, now that we have these fields, let’s do something with them.  We want to take the current values from the corresponding billing fields and copy them.  The following code evaluates each of the fields we just grabbed, finds an equivalent (eq) input value (val) in #billing_fields and sets the value of that element to the same value.

//copy the values from the #billing_fields inputs to the equiv inputs on the #shipping_fields
$(this).val( $('#billing_fields input').eq(i).val() );
}); 

The above code won’t affect select boxes, so we need to process them individually.  Using the “copy value” function of the jQuery Select Plugin, we will manually put the value of the billing country into a variable, and then set the value of the corresponding shipping country to that variable.  Normally a value won’t do a whole lot to a select box, but the plugin allows the value to set the selectedindex, which is exactly what we want.

//won't work on drop downs, so get those values
var bcountry = $("#bcountry").val();
$(
"#scountry").selectOptions(bcountry); 

OK, all done.  So, if the checkbox is cleared, we want to set all these values back to empty.  As a usability enhancement (homework?) you could set this up to revert the shipping fields to whatever they were before the checkbox was clicked.  We’re using all the same tricks as above, so you should be able to see exactly what is going on.

else {

//for each input field
$('#shipping_fields input'':visible'document.body).each(function(i
//set shipping_fields inputs to blank
$(this).val(""); 
});
$(
"#scountry").selectOptions("");
}
}
);
});
</script> 

That’s all there is to it.  jQuery allows us to use a single line of javascript to change as many non-select box fields as necessary.  A little ingenuity and we can take care of those selects. 

Finally, here is a demo so you can see it in action.

2 Comments

posted on February 27, 2010 at 8:30am by Jhaura Wachsman:

Nice, thanks so much. Here it is modified NOT to use the Select Plugin and puts the default value back in…

http://pastebin.com/GPrfcDXy

posted on September 03, 2010 at 8:12pm by Adhesion:

Thanks for this post, it’s been a great learning tool for me.

I’ve had to copy a checkbox value and have it working as per below, but wondered if my code could be written better?

// checks the checkbox is checked
if ($(”#residential_address”).is(”:checked”)) {
$(”#shipping_fields”).checkCheckboxes(”#shipping_residential_address”, true);
}

// unchecks checkbox if checked
if ($(”#residential_address”).is(”:checked”)) {
$(”#shipping_fields”).unCheckCheckboxes(”#shipping_residential_address”, true);
}

Thanks again.

Leave a Comment

 Remember Me?

 Notify Me of Follow Up Comments?

Are you human? What animal barks? (3 character(s) required)