I am currently trying to populate a form with values fetched from mysql database. The form is very dynamic thanks to the help of jquery. Input fields can be added or deleted with a button click. For more background information in the structure of the form check my previous. I am running into difficulties in a way to populate this form with values from the database. I have foreach loop that fetches the values and places them in a JSON object. How can autopolulate the fields with these values? JSFIDDLE
Edit- I am aware there exists angular, ember, knockout and other js technologies for the job but for learning reasons I decided to this without the help of a commercial framework.
Form
<script type='text/template' data-template='item'>
<ul class="clonedSection">
<li style="list-style-type: none;">
<label>
<input class="main-item" data-bind = 'firstItem' type="checkbox" />First Item</label>
<ul class="sub-item" data-bind ='subItem' style="display: none;">
<li style="list-style-type: none;">
<label>
<input type="checkbox" />Sub Item</label>
</li>
</ul>
</li>
<li style="list-style-type: none;">
<label>
<input class="main-item" data-bind ='secondItem' type="checkbox" />Second Item</label>
<ul class="sub-item" style='display: none;' data-bind='detailsView'>
<li style="list-style-type: none;">How many items:
<select class="medium" data-bind ='numItems' required>
<option value="" selected>---Select---</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</li>
<li style="list-style-type: none;">
<div data-bind ='items'>
Item # {number}
<select>
<option value='initial' selected='true' >--- Select ---</option>
<option value='Bananas'>Bananas</option>
<option value='Apples'>Apples</option>
<option value='Oranges'>Oranges</option>
</select>
</div>
</li>
</ul>
</li>
</ul>
</script>
<input type='button' value='add' data-action='add' />
<input type='button' value='remove' data-action='remove' />
getItems.php
header("Content-type: application/json");
$db_select = $db_con->prepare("SELECT
p.firstItem,
p.subItem,
p.secondItem,
p.itemNames,
case itemNames when null then 0
when '' then 0
else
(LENGTH(itemNames) - LENGTH(replace(itemNames, ',', '')) +1)
end
as numItems
FROM items_list p
");
if (!$db_select) return false;
if (!$db_select->execute()) return false;
$results = $db_select->fetchAll(\PDO::FETCH_ASSOC);
// check that the 'id' matches up with a row in the databse
if(!empty($results))
$responses = array();
foreach ($results as $value){
$responses[] = array(
'firstItem' => ($value['firstItem'] == '1' ? true : false),
'subItem' => ($value['subItem'] == '1' ? true : false),
'secondItem' => ($value['secondItem'] == '1' ? true : false),
'numItems' => $value['numItems'],
'items' => array_map('trim', explode(',', $value['itemNames']))
);
}
echo json_encode($responses);