Search code examples
jqueryajaxclone

How to call AJAX function after form elements are cloned using jQuery?


I have a dynamic form that can be cloned, using the SheepIt! plugin to clone my form elements. My form has a dynamic set of dropdown boxes, where the second dropdown box display a set of values based on the selection from the first dropdown box.

My problem is that the dynamic function of the dropdown boxes is not functioning on cloned dropdowns, and only works for the first dropdown on the page.

Any ideas why this is happening?

I created a fiddle so you can see how the SheepIt! plugin works, http://jsfiddle.net/DeJch/1/, but the add/delete functions are not working in fiddle.

Do I have to recall the AJAX after the clone is made?

Maybe something like $('#container_add').live('click', function() { */ */ });?

HTML:

<div>
    <label>Item:</label>
    <select class="item" name="item" id="item"> 
        <option value="">Select</option>
        ...
    </select>
</div>          
<div>
    <label class="label>Options:</label>
    <select class="options" name="options" id="options">
        ...
    /select>
</div>  

Javascript:

$(document).ready(function(){   

    var sheepItForm = $('#clone').sheepIt({
        separator: '',
        allowRemoveLast: true,
        allowRemoveCurrent: true,
        allowAdd: true,
        maxFormsCount: 3,
        minFormsCount: 1,
        iniFormsCount: 1
    });

    $(".item").change(function () { 

      var group_id = $(this).val();
      var self = $(this); // Added line

      var $children = $(this).parent().next().children('select.options')

       $.ajax({
            type: "POST", 
            url: "../../db/groups.php?id=" + group_id, 
            dataType: "json",
            success: function(data){    
                $children.empty()
                $children.append('<option value="">Select</option>');           
                $.each(data, function(i, val){    
                   $children.append('<option value="' + val.group_id + '">' + val.name + '</option>');
                });
                $children.focus();
            },
            beforeSend: function(){
                $children.empty();
                $children.append('<option value="">Loading...</option>');
            },
            error: function(){
                $children.attr('disabled', true);
                $children.empty();
                $children.append('<option value="">No Options</option>');
            }
        })  

    }); 

})

Solution

  • Do I have to recall the AJAX after the clone is made?

    Maybe something like $('#container_add').live('click', function() { */ */ });?
    

    Pretty much yes, but don't use .live() event as it is now deprecated. Use the on() event instead. Syntax is pretty much the same

    $('#container_add').on('click', function() { */ */ });
    

    The on event is much similar to live. Take a look at http://api.jquery.com/live/