I am using PHP to dynamically generate some fields in a form (here is jsFiddle with full code http://jsfiddle.net/KBYC5/1/).
<?php
$contacts= array('CONTRACT MANAGER', 'MEDICAL DIRECTOR', 'UTILIZATION MANAGER', 'QUALITY IMPROVMENT MANAGER ', 'CHIEF MEDICAL DIRECTOR', 'CMO', 'AUTHORIZATION MANAGER', 'CUSTOMER SERVICE MANAGER');
foreach ($contacts as $contact) //TODO add something to check if contact already exists and don't show checkbox if it does
{
echo "<li>
<label>" . ucwords(strtolower($contact)) . "</label>" . inp_return('contact[]', 45) . " <input type='hidden' value='$contact' name='title' />
<ul>
<li><label> Rating: </label>" . inp_return('rating[]',3) . "</li>
<li><label>Phone: </label>" . inp_return('contact_phone[]',13, 'phone'). "</li>
<li><label>Ext: </label>" . inp_return('ext[]', 8) . "</li>
<li><label>Create Referral Contact</label> " . cbox_return('create_contact[]') . "</li>
</ul>
<div class='clear'></div>
</li>
";
}
?>
As you can see, each will have a hidden input with the value from $contacts. What I am then trying to do is use jQuery to check for the value in the hidden input field, compare it to the “title” property of the JSON object, and then, if they are the same, fill in all of the form values. My script section is here:
<script type='text/javascript'>
var contacts = $.parseJSON('[{"id":1,"name":"TEST CONTACT","title":"CONTRACT MANAGER","rating":5,"phone":"(000)000-0000","ext":"1111","rfcode":"0000"},
{"id":2,"name":"TEST2 CONTACT","title":"MEDICAL DIRECTOR","rating":2,"phone":"(111)111-1111","ext":"2222","rfcode":"0000"}]');
$(document).ready(function () {$("#contracting_info ul li").each(function (){
for (var i in contacts)
{
alert($(this).children("input[name='title']").val()); die;
var title = contacts[i].title
if (title == $(this).children("input[name='title']").val())
alert('made it here');
}
});
});
How can I load the contact[] element in each list item with the value from the JSON array (where title matches hidden title element)? For example, I want the Contract Manager’s contact[] field to have TEST CONTACT in it.
Here is the script section that worked for my problem.
Unfortunately, it means I have to loop through each list item element, then loop through all of the contacts (so I end up looping through contacts for each li). It is working properly though.
Hopefully this helps someone else that is trying to dynamically fill form fields with information from a json object (where the form fields post to an array).