0
我有一个“发送”表单,我想通过简单地选中一个复选框,让用户能够将其输入值复制到其“结算”表单中。使用JQuery将一个表单的值复制到另一个表单
我已经编写了一个可行的解决方案 - 但是,我对jQuery有些不熟悉,并希望对我如何实现这一点进行一些批评。这是否做得好 - 您推荐的任何重构?
任何意见将不胜感激!
脚本
<script type="text/javascript">
$(function() {
$("#copy").click(function() {
if($(this).is(":checked")){
var $allShippingInputs = $(":input:not(input[type=submit])", "form#shipping");
$allShippingInputs.each(function() {
var billingInput = "#" + this.name.replace("ship", "bill");
$(billingInput).val($(this).val());
})
//console.log("checked");
} else {
$(':input','#billing')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
//console.log("not checked")
}
});
});
</script>
表单
<div>
<form action="" method="get" name="shipping" id="shipping">
<fieldset>
<legend>Shipping</legend>
<ul>
<li>
<label for="ship_first_name">First Name:</label>
<input type="text" name="ship_first_name" id="ship_first_name" value="John" size="" />
</li>
<li>
<label for="ship_last_name">Last Name:</label>
<input type="text" name="ship_last_name" id="ship_last_name" value="Smith" size="" />
</li>
<li>
<label for="ship_state">State:</label>
<select name="ship_state" id="ship_state">
<option value="RI">Rhode Island</option>
<option value="VT" selected="selected">Vermont</option>
<option value="CT">Connecticut</option>
</select>
</li>
<li>
<label for="ship_zip_code">Zip Code</label>
<input type="text" name="ship_zip_code" id="ship_zip_code" value="05401" size="8" />
</li>
<li>
<input type="submit" name="" />
</li>
</ul>
</fieldset>
</form>
</div>
<div>
<form action="" method="get" name="billing" id="billing">
<fieldset>
<legend>Billing</legend>
<ul>
<li>
<input type="checkbox" name="copy" id="copy" />
<label for="copy">Same of my shipping</label>
</li>
<li>
<label for="bill_first_name">First Name:</label>
<input type="text" name="bill_first_name" id="bill_first_name" value="" size="" />
</li>
<li>
<label for="bill_last_name">Last Name:</label>
<input type="text" name="bill_last_name" id="bill_last_name" value="" size="" />
</li>
<li>
<label for="bill_state">State:</label>
<select name="bill_state" id="bill_state">
<option>-- Choose State --</option>
<option value="RI">Rhode Island</option>
<option value="VT">Vermont</option>
<option value="CT">Connecticut</option>
</select>
</li>
<li>
<label for="bill_zip_code">Zip Code</label>
<input type="text" name="bill_zip_code" id="bill_zip_code" value="" size="8" />
</li>
<li>
<input type="submit" name="" />
</li>
</ul>
</fieldset>
</form>
</div>
这是一个非常好的想法,我试图做类似的事情。我试着测试你的例子,看看它是如何工作的,但我无法使它工作 – AdRock 2011-10-24 19:25:22