Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

How to refactore this

    $("#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());
    })

I try to use an array like this and looping to bind all event but it isn't work

    var control = [
        { source: "txtShippingAddressFullName", destination: "txtBillingAddressFullName" },
        {source : "txtShippingAddress" , destination : "txtBillingAddress"},
        {source : "txtShippingPostalCode" , destination : "txtBillingPostalCode"},
        {source : "txtShippingPhoneNumber" , destination : "txtBillingPhoneNumber"},
        {source : "ddlShippingCity" , destination : "ddlBillingCity"}
    ];
share|improve this question

3 Answers 3

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

share|improve this answer

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());
});
share|improve this answer

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());
});
share|improve this answer
    
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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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