JQuery form field replace help, pretty please

Hello,

I have a form which collects billing address and shipping address information. I am trying to set up a checkbox to copy over shipping address form fields to billing address form fields, using JQuery. The two forms are identical except that the field names contain either Ship or Bill for each form item, eg:

Shipping First Name: <input type=“text” name=“Customer_ShipFName”>
Billing First Name: <input type=“text” name=“Customer_BillFName”>

Shipping fields are in a div with id “ship-to-fields” and billing fields are in a div with id “bill-to-fields.”

I can’t use ids to target the fields because a couple of the fields are select inputs that are dynamically generated (that is, I can’t control the output of the select tag).

I have the following function, which works great if the names of both ship to and bill to fields have the same name:


	$(function() {
	  $("#sameAsShipTo").change(function() {
	    if (this.checked) {
	      $("#ship-to-fields input").each(function() {
	        var self = $(this);
	        $("#bill-to-fields input[name='" + self.attr("name").replace(/ship-to-fields/, "bill-to-fields") + "']").val(self.val());
	      });
	    }
	  });
	});

What I need to know is how to tell it to replace _Ship with _Bill in the name attribute of each form field. I know just enough JQuery to copy/paste/slightly tweak, and I’m afraid of breaking everything if I try to get creative. Can anyone help?

Thanks,
Leanne

The jQuery selectors allow you to select the fields ending in _ship with the attribute ends with selector

You can then use standard string manipulation techniques to replace _ship with _bill with the replace command.

Something like this:


$('#ship-to-fields input[name$="_ship"]').each(function () {
    var billingName = this.name.replace('_ship', '_bill');
    this.form.elements[billingName].value = this.value;
});

Thank you so very much. I had to tweak it a little bit to use Attribute Starts With instead but it’s now working perfectly. Here’s the finished product:


$(function() {
	  $("#sameAsShipTo").change(function() {
	    if (this.checked) {
	      $('#ship-to-fields input[name^="Customer_Ship"], #ship-to-fields select[name^="Customer_Ship"]').each(function () {
   		 	var billingName = this.name.replace('Customer_Ship', 'Customer_Bill');
    		this.form.elements[billingName].value = this.value;
		  });
	    }
	    
	    else {
	   	  $('#ship-to-fields input[name^="Customer_Ship"], #ship-to-fields select[name^="Customer_Ship"]').each(function () {
   		 	var billingName = this.name.replace('Customer_Ship', 'Customer_Bill');
    		this.form.elements[billingName].value = '';
		  });
	    
	    }

	  });
	});