2

I have a dynamic form and use 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 this is an "edit" form, so existing data need to be injected into the form elements when the page loads. Fortunately, SheepIt allows for data-injection; however, I am having difficulties because the dropdown boxes in my form are "dynamic" as described above.

Any ideas on how I can get around this and inject the data into my dynamic form elements?

Javascript:

<script>
$().ready(function() {

    var sheepItForm = $('#clone').sheepIt({
        separator: '',
        allowRemoveLast: true,
        allowRemoveCurrent: true,
        allowAdd: true,
        maxFormsCount: 3,
        minFormsCount: 1,
        iniFormsCount: 1,
        data: [
            {
                'item_1': 'CLONE #1 ITEM 1 DATA HERE',
                'item_2': 'CLONE #1 ITEM 2 DATA HERE',
            },
            {  
                'item_1': 'CLONE #2 ITEM 1 DATA HERE',
                'item_2': 'CLONE #2 ITEM 2 DATA HERE',
            },
            ...
        ]        
    });

    $("#item_1").live('change', function () {   

      var group_id = $(this).val();
      var self = $(this); 

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

       $.ajax({
            type: "POST", 
            url: "../../db/groups.php?item_1_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>');
            }
        })  

    });

});
</script>

HTML:

<label id="item_1_label" for="item_1" class="label">#1:</label>
<select id="item_1" name="item_1" />
    <option value="">Select</option>
    <?php
        $sth = $dbh->query ("SELECT id, name, level 
                             FROM groups
                             WHERE level = '1'
                             GROUP by name
                             ORDER BY name");                                   
        while ($row = $sth->fetch ()) { 
            echo '<option value="'.$row['id'].'">'.$row['name'].'</option>'."\n";       
        }
     ?>
</select>

<label id="item_2_label" for="item_2" class="label">#2:</label>
<select id="item_2" name="item_2" />                        
</select>

PHP (groups.php)

<?php

require_once('../includes/connect.php');        

$item_1_id = $_GET['item_1_id'];

$dbh = get_org_dbh($org_id);

$return_arr = array();

$sth = $dbh->query ("SELECT id, name, level 
                     FROM groups
                     WHERE level = '2'
                     AND parent = $item_1_id
                     GROUP by name
                     ORDER BY name");   

while ($row = $sth->fetch ()) { 

    $row_array = array("name" => $row['name'], 
                       "id" => $row['id']); 

    array_push($return_arr,$row_array);     
}

echo json_encode($return_arr);

?>  

Sample JSON Output:

[{"name":"A","id":"0"},{"name":"B","id":"1"},{"name":"C","id":"2"}]
Michael
  • 2,276
  • 15
  • 49
  • 80

2 Answers2

1

Is it calling the Ajax? It's possible that the following isn't being triggered as it's dynamically loaded.

$("#item_1").change(function () {

Maybe try changing it to

$("#item_1").live("change",function () {

At the least it might be worth throwing in an alert() in there to see if it's being triggered.

shadylane
  • 87
  • 2
  • 10
1

The problem is that you are using IDs to control your "dynamic" select boxes, but by adding sheepIt into the mix you are cloning these elements and the new pairs no longer fit your selectors. I'd start by using classes for targeting things that you want to behave similarly:

    <select id="item_1" name="item_1" class="firstSelect"/>
...
    <select id="item_2" name="item_2"  class="secondSelect"/>   

Then you can have your change handler work for ANY of the groups, not just the original one:

$(".firstSelect").live('change', function () {   
  ...
  var $children = $(this).parent().next().children('.secondSelect')

There are a couple more changes to make, but the idea is keep your code as general as possible, there is no reason to target unique characteristics if you want general behaviour. groups.php shouldn't care WHO is sending a selection, just WHICH selection was made. It can then return the appropriate options.

Similarly your javascript doesn't need to be pinned down to unique IDs, you've already gone half way by including traversal in your handler. Why else would you be using

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

to move your way over to the matching select box when you clearly could have just used

var $children = $('#item_2')
Sinetheta
  • 9,189
  • 5
  • 31
  • 52