我的代码很远,就是将结算地址复制到表单上的送货地址:
JQUERY
$("#toshipping_checkbox").on("click",function(){
var formid = $(this).closest("form").attr("id");
var idsplit = formid.split('_');
console.log(idsplit[0]);
var ship = $(this).is(":checked");
$("[id^='form1_shipping_']").each(function(){
var tmpID = this.id.split('form1_shipping_')[1];
$(this).val(ship?$("#form1_"+tmpID).val():"");
});
});
HTML
<h2>Billing Address</h2>
<div>
<label class="required" for="form1_address_1">Address 1</label>
<input id="form1_address_1" name="address_1" type="text" required="required" />
</div>
<div>
<label for="form1_address_2">Address 2</label>
<input id="form1_address_2" name="address_2" type="text" />
</div>
<div>
<label for="form1_city">City</label>
<input id="form1_city" name="city" type="text" />
</div>
<h2>Shipping Address</h2>
<label for="toshipping_checkbox">Tick this box if Shipping Address and Billing Address are the same.</label>
<input type="checkbox" id="toshipping_checkbox">
<div>
<label class="required" for="form1_shipping_address_1">Address 1</label>
<input id="form1_shipping_address_1" name="shipping_address_1" type="text" required="required" />
</div>
<div>
<label for="form1_shipping_address_2">Address 2</label>
<input id="form1_shipping_address_2" name="shipping_address_2" type="text" />
</div>
<div>
<label for="form1_shipping_city">City</label>
<input id="form1_shipping_city" name="shipping_city" type="text" />
</div>
现在我需要用form1
替换idsplit[0]
的每个实例。我试过但它一直都失败了。这样做的最佳方式是什么?
要获得更多说明,我的CMS会将form1
添加到我的输入ID中,因此无法删除。此外,如果它是页面上的第二个表单,它将是form2
,所以我需要从DOM获取值作为变量。我已经完成了这个,现在我只需要将变量放到我的jQuery中,无论我目前在哪里form1
答案 0 :(得分:0)
这是我最终得到的javascript - 将idsplit
传递给变量
$("#toshipping_checkbox").on("click",function(){
var formid = $(this).closest("form").attr("id");
var idsplit = formid.split('_');
var splitid =idsplit[0];
var ship = $(this).is(":checked");
$('[id^="' + splitid + '_shipping_"]').each(function(){
var tmpID = this.id.split(splitid + '_shipping_')[1];
$(this).val(ship?$('#' + splitid + '_' + tmpID).val():'');
});
});