Reputation: 52523
I have a form that requires billing and shipping information. As you can imagine, I have textboxes with repetitive info for 95% of cases. However, in the event that someone wants to be billed in one place and have their items shipped elsewhere, we need to account for that.
What I would like to do to enhance user experience is have a button that transfers all the data from the Billing fields to their Shipping counterparts. Is there any way to do this easily in jQuery? Right now I have it done on the server with typical 1 to 1 mapping (ie, shippingfirstname.text = billingfirstname.text
, etc), but I was wondering if I could save a postback with some simple jQuery. However, with the way that .NET mangles ID's, I've found that it's probably more work to set up all the client IDs and then do the transfer. Am I missing something?
Thanks
Upvotes: 1
Views: 682
Reputation: 106332
I think that the best solution to this is to ask for the billing address, then have a simple checkbox that says "Ship to billing address" - checked by default - when someone unchecks that checkbox, the "shipping" fields show up. The server side should still handle copying that information from billing->shipping fields, not all users use javascript.
As far as a jQuery way to copy from one set of fields to another you could try something along the lines of:
// just so we are only working within the one form we want to work with:
var $form = $('#ourform');
// all fields whos names begin with 'billing':
$('input[name^=billing]', $form).each(function() {
var $field = $(this);
// replace the billing with shipping
var newName = $field.attr('name').replace(/^billing/, 'shipping');
// look for an input named shipping instead of billing,
// and set its value to our value.
$('input[name='+newName+']', $form).val($field.val());
});
If you are using the [ and ] characters in your input names - you will need to escape them with this line of code:
newName = newName.replace(/\[/, '\\[').replace(/\]/, '\\]');
Upvotes: 2
Reputation: 532435
This depends on the fields being named exactly the same except for the billing/shipping and that only those fields that you want to copy contain "billing".
function copyAddress() {
$('input[name*=billing]').each( function() {
var $this = $(this);
var shippingName = $this.attr('name').replace(/billing/,'shipping');
$('input[name$=' + shippingName + ']').val( $this.val() );
});
}
Upvotes: 5