Dylan
Dylan

Reputation: 412

Dynamically adding a table row with jquery, then add auto populate select box in each new row

Hey, guys, I tried to ask this yesterday but I didn't explain myself clearly or simply enough.

I have a form that is setup in a table. User can add new rows (and more form elements) as they please. Each row of this form needs to have its own separate select box and corresponding subcategory select box.

So basically...

Name | Select
xxxxxx | [category select] [subcategory select]
xxxxxx | [category select] [subcategory select]
xxxxxx | [category select] [subcategory select]

You get the idea. :)

Right now any rows added have a broken version of the auto populate.

Any suggestions as to how to get this to work?

Here is the auto populate code and add table row code I'm using, if this helps racks anyone's brain. I'll gladly scrap everything if someone has an answer they feel is better.

Free cookie for a solution where I can add/remove form rows. :)

// auto populate select code

 $(document).ready(function(){
            $("#selectionresult").hide();

            $("#selection").change( function() {
                $("#selectionresult").hide();
                $("#result").html("Retrieving ...");
                $.ajax({
                    type: "POST",
                    data: "data=" + $(this).val(),
                    url: "include/javascript_population.php",
                    success: function(msg){
                        if (msg != ""){
                            $("#selectionresult").html(msg).show();
                            $("#result").html("");
                        }
                        else{
                            $("#result").html("<em>No item result</em>");
                        }
                    }
                });
            });
        });


// add table row code

  $(document).ready(function() {
        $("#add").click(function() {
          $('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');

          return false;
        });
    });

    $("#mytable tbody>tr:last").each(function() {this.reset();});     

Any help would be totally appreciated everybody. Thanks in advance. :)

Upvotes: 1

Views: 2799

Answers (1)

nicholasklick
nicholasklick

Reputation: 1212

You may have issues with ID's clashing and event binding. Try using live();

Your events are getting unbound when you clone and move DOM elements around.

Try this:

$("#add").live("click", function() {
$("#selection").live("change", function() {

Also it looks like you may be duplicating ID's. Check and make sure that #selection, #selectionresult, etc are not being cloned.

Upvotes: 1

Related Questions