I am fairly new to jQuery and JSON and have run into a problem I haven’t been able to solve. I have a textbox that I would like a user to start typing a person’s name and when he/she selects the name, it autopopulates another textbox with their email address.
My code is as follows. Any help getting this to work would be greatly appreciated. Thanks so much in advance!
Markup
<input type="text" id="person_name" class="required" />
<input type="text" id="person_email_address" class="required email" />
jQuery
$( "input#person_name" ).autocomplete({
source: "/autoComplete.aspx",
dataType: "json",
minLength: 1,
select: function( event, ui ) {
//set email textbox to the email field of the selected item.
}
});
autoComplete.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string term = Request.QueryString["term"];
if (!string.IsNullOrEmpty(term))
{
string sql = string.Format("select * from users where first_name like '%{0}%' or last_name like '%{0}%'", term);
DataTable dt = GetTable(sql);
foreach (DataRow dr in dt.Rows)
{
string name = dr["first_name"].ToString() + dr["last_name"].ToString();
string email = dr["email"].ToString();
}
Response.ContentType = "application/json";
Response.Write("what goes here so i can access both email and name in the select function?");
}
}
Use something like this in your code-behind:
That should get you the correct JSON, with name as the label, and email as the value. Now in the Javascript select callback function, set the email textbox to the correct value:
NOTE
Per comments, the above is invalid without modification. The JSON values have to be wrapped in double quotes.