表单内的jQuery clone()问题

时间:2010-12-30 15:23:14

标签: jquery forms jquery-selectors

我正在使用jQuery在CakePHP中创建一个表单。我的问题是我需要能够使用jQuery克隆表单的某些字段。表单是预订,我需要克隆客户详细信息以添加超过1个客户(如果是一个组)。

我正在使用此代码:

var idx = 0;
        $(document).ready(function() {
            $("#addCustomerFields").click(function() {
                idx = idx + 1;
                var x = $("#Cliente").clone();
                $(x)
                    .attr("id", "Client." + idx)
                    .find("label").each(function() {
                        $(this).attr("for", $(this).attr("for").replace(".0", "." + idx));
                    })
                    .end()
                    .find("input").each(function() {
                        $(this)
                            .attr("id", $(this).attr("id").replace(".0", "." + idx))
                            .attr("name", $(this).attr("name").replace("[0]", "[" + idx + "]"));

                        //this.value = '';
                    })

                $("#CustomerFields").append(x);
            });
        });

它工作正常,但仅适用于文本输入字段。下拉(选择)不起作用。看起来,脚本不会更改select(id和name)的属性。当我添加2个客户时,第一个男性和第二个女性在数据库中,第一个显示为女性,第二个没有性别。每个字段都有自己的名称和ID:客户端[0] [名字],客户端[0] [性别]等等。当我克隆时,我增加了数字,这只是在文本输入中发送。

观点是:

<fieldset id="Cliente">
        <legend class="legend"><?php __('Client Info'); ?></legend>
    <?php

        //this is select
        echo $this->Form->input('Client.0.sex_id', array(
            'label'=>'Gender', 
            'div'=>'float IconSex',
            )
        );
        echo $this->Form->input('Client.0.firstname', array(
            'label'=>'First name', 
            'div'=>'float IconUser'
            )
        );
        echo $this->Form->input('Client.0.lastname', array(
            'label'=>'Last name', 
            'div'=>'float IconUser'
            )
        );

        //another select
        echo $this->Form->input('Client.0.country_id', array(
            'label'=>'Country', 
            'div'=>'clear IconCountry',
            'default'=>'121'
            )
        );

    ?>

    </fieldset><div id="CustomerFields"></div>

    <?php 
    echo $this->Html->div('IconAdd', 'Add customer.', array(
            'id'=>'addCustomerFields', 
            )
        );
    ?>

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您只使用当前代码.find("input").each(function(...

选择输入元素

尝试.find(":input")match所有输入(选择,输入,textarea等)

或只是使用

$('select, input')

匹配输入并选择

相关问题