4
\$\begingroup\$

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());
})
\$\endgroup\$

3 Answers 3

5
\$\begingroup\$

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());
});
\$\endgroup\$
1
  • \$\begingroup\$ This solution is more flexible since it doesn't restrict a rule for the new name. \$\endgroup\$ Oct 12, 2012 at 13:15
5
\$\begingroup\$

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

\$\endgroup\$
4
\$\begingroup\$

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());
});
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.