我有一個動態的形式,並使用SheepIt!插件克隆我的表單元素。我的表單有一組動態下拉框,其中第二個下拉框會根據第一個下拉框中的選擇顯示一組值。如何使用jQuery插件將數據注入到克隆下拉框中?
我的問題是,這是一個「編輯」的形式,所以現有的數據需要被注入到表單元素在頁面加載時。幸運的是,SheepIt允許data-injection;然而,我有困難,因爲我的表單中的下拉框是「動態的」,如上所述。
我如何能解決這個和數據注入到我的動態表單元素任何想法?
的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);
?>
樣品JSON輸出:
[{"name":"A","id":"0"},{"name":"B","id":"1"},{"name":"C","id":"2"}]
所有正在與AJAX調用,這是嚴格的數據打針我我有困難。 – Michael 2012-01-12 01:43:11
是不是被刪除了.on? – SpYk3HH 2012-01-16 23:44:36