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"}]