将所选选项复制到另一个选项

时间:2015-10-19 22:48:45

标签: javascript jquery html

我觉得可能有一个答案,如果是这样,我找不到。

我有表格,结算和送货地址。我有一个复选框,上面写着"结算与送货地址相同"选中此选项后,我想将所有值从帐单邮寄地址部分复制到送货地址选择。我已经能够复制文本了,但是国家的选择选项似乎比预期的要复杂。这就是我到目前为止所拥有的:

<select class="span12" id="BillingCountry" name="BillingCountry">
    <option value="AF">AFGHANISTAN</option>
    <option value="AX">ALAND ISLANDS</option>
    <option value="AL">ALBANIA</option>
</select>

<select class="span12" id="ShippingCountry" name="ShippingCountry">
    <option value="AF">AFGHANISTAN</option>
    <option value="AX">ALAND ISLANDS</option>
    <option value="AL">ALBANIA</option>
</select>

<label><input type="checkbox" id="duplicate-address" name="duplicate-address" value="shipping same as billing">&nbsp;&nbsp;Shipping address is same as billing</label>

$('#duplicate-address').click(function(e) {
    if( $('#duplicate-address').prop('checked') ){
        $("#ShippingAddress").val($("#BillingAddress").val()); //works
        $("#ShippingCountry").val($("#BillingCountry").val());
    }
});

因此,如果我在结算国家阿尔巴尼亚选择并按下复选框,我希望看到运送国家也选择阿尔巴尼亚。任何正确方向的指针都会很棒

2 个答案:

答案 0 :(得分:1)

我不确定我的问题是对的。在这里!

&#13;
&#13;
var shipping = jQuery('#ShippingCountry');
var billing = jQuery('#BillingCountry');

billing.on('change', function(e){
    var selected = jQuery('option:selected', this);
    shipping.val(selected.val());
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="span12" id="BillingCountry" name="BillingCountry">
    <option value="AF">AFGHANISTAN</option>
    <option value="AX">ALAND ISLANDS</option>
    <option value="AL">ALBANIA</option>
</select>

<select class="span12" id="ShippingCountry" name="ShippingCountry">
    <option value="AF">AFGHANISTAN</option>
    <option value="AX">ALAND ISLANDS</option>
    <option value="AL">ALBANIA</option>
</select>

<label><input type="checkbox" id="duplicate-address" name="duplicate-address" value="shipping same as billing">&nbsp;&nbsp;Shipping address is same as billing</label>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果您想要复选框状态更改,请在#ShippingCountry中选择与#BillingCountry中相同的选项,此处代码为:

<select class="span12" id="BillingCountry" name="BillingCountry">
    <option value="AF">AFGHANISTAN</option>
    <option value="AX">ALAND ISLANDS</option>
    <option value="AL">ALBANIA</option>
</select>

<select class="span12" id="ShippingCountry" name="ShippingCountry">
    <option value="AF">AFGHANISTAN</option>
    <option value="AX">ALAND ISLANDS</option>
    <option value="AL">ALBANIA</option>
</select>

<label><input type="checkbox" id="duplicate-address" name="duplicate-address" value="shipping same as billing">&nbsp;&nbsp;Shipping address is same as billing</label>

$('#duplicate-address').click(function(e) {
    if( $('#duplicate-address').prop('checked') ){
     $('#ShippingCountry').val($('#BillingCountry option:selected').val())
    }
});

JSFIDDLE