开发者

jQuery clone() problem inside a form

I am making a form in CakePHP with jQuery. My problem is that I need to be able to clone some fields of the form with jQuery. The form is a reservation and I need to clone customer details to add more than 1 customer (if it is a group).

I am using this code:

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开发者_如何学C + "]"));

                        //this.value = '';
                    })

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

It works OK but only with text input fields. Drop downs (select) don't work. It looks like the attributes of select (id and name) are not changed by the script. When I add 2 customers, first one male and the second one female in the database the first one appears as female and second is without sex. Each field has its name and id: Client[0][Firstname], Client[0][Sex] and etc. When I clone I increase the number and this wokrs only in text inputs.

The view is:

<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', 
            )
        );
    ?>

Any ideas?


You are only selecting input elements with your current code .find("input").each(function(...

Try .find(":input") to match all inputs (selects, inputs, textarea etc)

or just use

$('select, input')

to match inputs and selects

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜