将结算地址重复到送货地址

时间:2016-02-10 12:34:02

标签: jquery html

我有以下代码将输入的结算地址复制到送货地址表单:

HTML

<b>Billing Address</b>

<form>

   Address 1:
   <input type="text" id="billing_address_1">

   Address 2:
   <input type="text" id="billing_address_2">

   City:
   <input type="text" id="billing_city">

   <input type="checkbox" id="billingtoshipping_checkbox">
   <em>Check this box if Shipping Address and Billing Address are the same.</em>
   <b>Shipping Address</b>

   Address 1:
   <input type="text" id="shipping_address_1">

   Address 2:
   <input type="text" id="shipping_address_2">

   City:
   <input type="text" id="shipping_city">

</form>

JQUERY

$("#billingtoshipping_checkbox").change(function(){
    if($(this).is(":checked")){
        $("[id^='shipping_']").each(function(){
            data=$(this).attr("id")
            tmpID = data.split('shipping_');
            $(this).val($("#billing_"+tmpID[1]).val())
        })
    }else{
        $("[id^='shipping_']").each(function(){
            $(this).val("")
        })

      }
})

现在我需要在帐单邮寄地址输入ID上没有billing_的情况下使其工作,我无法解决这个问题。这是由于我使用的CMS,我无法控制ID。 ID的其余部分将与运费匹配,例如address_1如果勾选复选框,shipping_address_1应显示在address_2中,shipping_address_2应显示在city中,依此类推,shipping_city会显示在MagicalRecord.setupAutoMigratingCoreDataStack() let moc = NSManagedObjectContext.MR_defaultContext() moc.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

  1. change更改为click,因为它是复选框的更好的事件处理程序
  2. 已删除“结算”
  3. 在需要的地方添加了var
  4. 使用三元缩短代码
  5. $("#toshipping_checkbox").on("click",function(){
        var ship = $(this).is(":checked");
        $("[id^='shipping_']").each(function(){
          var tmpID = this.id.split('shipping_')[1];
          $(this).val(ship?$("#"+tmpID).val():"");
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <b>Billing Address</b>
    
    <form>
    
       Address 1:
       <input type="text" id="address_1">
    
       Address 2:
       <input type="text" id="address_2">
    
       <input type="checkbox" id="toshipping_checkbox">
       <em>Check this box if Shipping Address and Billing Address are the same.</em>
       <b>Shipping Address</b>
    
       Address 1:
       <input type="text" id="shipping_address_1">
    
       Address 2:
       <input type="text" id="shipping_address_2">
    
    </form>