# Synchronizing billing fields with the corresponding shipping fields

How can I refactor this redundant code?

$("#txtShippingAddressFullName").change(function () {$("#txtBillingAddressFullName").val($(this).val()); })$("#txtShippingAddress").change(function () {
$("#txtBillingAddress").val($(this).val());
})

$("#txtShippingPostalCode").change(function () {$("#txtBillingPostalCode").val($(this).val()); })$("#txtShippingPhoneNumber").change(function () {
$("#txtBillingPhoneNumber").val($(this).val());
})

$("#ddlShippingCity").change(function () {$("#ddlBillingCity").val($(this).val()); })  ## 3 Answers The prettiest way to do it, would be with HTML 5 data attribute: <input id="txtShippingAddress" data-syncwith-id="txtBillinAddress"> <input id="txtShippingPostalCode" data-syncwith-id="txtBillingPostalCode"> <input id="txtShippingAddressFullName" data-syncwith-id="txtBillinAddressFullName">  Then in your javscript: $("input[data-syncwith-id]").change(function (event) {
$("#" +$(this).data("syncwith-id")).val($(this).val()); });  • This solution is more flexible since it doesn't restrict a rule for the new name. – Ufuk Hacıoğulları Oct 12 '12 at 13:15 Since I don't know your markup, I don't know for sure if this will work, but it might $("input[id*=Shipping]").change(function (event) {
var billingId = this.id.replace('Shipping', 'Billing');
$("#" + billingId).val($(this).val());
});


Basically, get every input with "Shipping" in its id, and when such an input changes, use its id to determine the corresponding billing-input.

Edit: While this solution is a neat little demonstration of the attribute-value-contains selector, it is - as the other answers have pointed out - better to use a class or data-attribute

Improving Flambino's answer, I think you should create a class for these elements and select them by the class.

$(".elements-to-replace").change(function (event) { var billingId = this.id.replace('Shipping', 'Billing');$("#" + billingId).val(\$(this).val());
});