jQuery - 为什么不选择盒子信息重复,但其余的将

时间:2011-04-18 20:40:02

标签: jquery

我正在使用下面的代码尝试在选中复选框时将信息从一组地址字段复制到另一组地址字段。除状态选择框(下拉框)外,所有这些都有效。这让我疯狂。

 //on page load
 $(document).ready(function() {

//when the checkbox is checked or unchecked
$('#copyaddress').click(function() {

    // If checked
    if ($(this).is(":checked")) {

        //for each input field
        $('#cc input', ':visible', document.body).each(function(i) {
            //copy the values from the billing_fields inputs
            //to the equiv inputs on the shipping_fields
            $(this).val($('#info input').eq(i).val());
        });
        //won't work on drop downs, so get those values
        var c_state = $("select#c_state").val();

        // special for the select
        $('select#cc_state option[value=' + c_state + ']').attr('selected', 'selected');

    } else {

        //for each input field
        $('#cc input', ':visible', document.body).each(function(i) {
            // put default values back
            $(this).val($(this)[0].defaultValue);
        });

        // special for the select
        $('select#cc_state option[value=""]').attr('selected', 'selected');
         }
     });
 });

1 个答案:

答案 0 :(得分:1)

设置单个值select元素的值时,您只需传递要选择的选项的文本值。 Check out the jQuery Documentation here on .val(value)

这可以修改......

    //won't work on drop downs, so get those values
    var c_state = $("select#c_state").val();

    // special for the select
    $('select#cc_state option[value=' + c_state + ']').attr('selected', 'selected');

到这个

$('select#cc_state').val($("select#c_state").val());