Link to home
Start Free TrialLog in
Avatar of Andrew
AndrewFlag for United States of America

asked on

Get GridView EditItemTemplate textbox value using jQuery?

I am having problems setting up a jQuery autocomplete textbox in a GridView EditItemTemplate.  I have it working in a DetailsView control, but am struggling with the GridView.  I am guessing below is what is causing the issue, but I get no errors in Google Dev Console...

$("#GridView1_Country")
                    .autocomplete({


<script type="text/javascript">
        $(document)
            .ready(function () {
                $("#GridView1_Country")
                    .autocomplete({
                        source: function (request, response) {
                            $.ajax({
                                type: "POST",
                                contentType: "application/json; charset=utf-8",
                                url: "../autocomplete.aspx/getCountries",
                                data: "{'prefixText':'" + $("#GridView1_Country").val() + "'}",
                                dataType: "json",
                                success: function (data) {
                                    response(data.d);
                                },
                                error: function (result) {
                                    alert("Error");
                                }
                            });
                        },
                        select: function (e, i) {
                            $("#GridView1_Country").val(i.item.val);
                        },
                        change: function (e, ui) {
                            if (!(ui.item)) e.target.value = "";
                        },
                        minLength: 1
                    });

Open in new window


 <asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="MID" DataSourceID="sqldsAll"
            AlternatingRowStyle-BackColor="WhiteSmoke" EditRowStyle-BackColor="Yellow" SelectedRowStyle-BackColor="GreenYellow">
            <Columns>
                <asp:ButtonField Text="Select" CommandName="Select" ButtonType="Button" />
                <asp:TemplateField ShowHeader="False" ItemStyle-Wrap="False">
                    <EditItemTemplate>
                         <asp:Button ID="btnUpdate" runat="server" CausesValidation="True" CommandName="Update" Text="Update" BackColor="Lime" />
                        &nbsp;<asp:Button ID="btnCancel" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Button ID="btnEdit" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" BackColor="Yellow" Visible="True" />
                        <asp:Button ID="btnDelete" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete" BackColor="Red" OnClientClick="return confirm('Are you sure you want to delete this record?');" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="MID" HeaderText="MID" SortExpression="MID" ReadOnly="True" InsertVisible="False" />
                <asp:BoundField DataField="AID" HeaderText="AID" SortExpression="AID" Visible="False"/>
                <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
                <asp:BoundField DataField="Pword" HeaderText="Pword" SortExpression="Pword" />
                <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
                <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
                <asp:BoundField DataField="Gender" HeaderText="Gender" SortExpression="Gender" />
                <asp:BoundField DataField="YOB" HeaderText="YOB" SortExpression="YOB" />
                <%--<asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />--%>
                <asp:TemplateField  HeaderText="Country" ItemStyle-Wrap="False">
                    <EditItemTemplate>
                        <asp:TextBox ID="Country" runat="server" CssClass="autosuggest" Text='<%#Bind("Country")%>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Country" runat="server" Text='<%#Eval("Country")%>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
                <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                <asp:BoundField DataField="PostalCode" HeaderText="PostalCode" SortExpression="PostalCode" />
                <asp:BoundField DataField="Latitude" HeaderText="Latitude" SortExpression="Latitude" />
                <asp:BoundField DataField="Longitude" HeaderText="Longitude" SortExpression="Longitude" />
                <asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
                <asp:BoundField DataField="CellPhone" HeaderText="CellPhone" SortExpression="CellPhone" />
                <asp:BoundField DataField="AltEmail" HeaderText="AltEmail" SortExpression="AltEmail" />
                <asp:BoundField DataField="Affiliation" HeaderText="Affiliation" SortExpression="Affiliation" />
                <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
                <asp:BoundField DataField="JobType" HeaderText="JobType" SortExpression="JobType" />
                <asp:BoundField DataField="ActivityType" HeaderText="ActivityType" SortExpression="ActivityType" />
                <asp:BoundField DataField="CreatedDate" HeaderText="CreatedDate" SortExpression="CreatedDate" />
                <asp:BoundField DataField="LastLoginDate" HeaderText="LastLoginDate" SortExpression="LastLoginDate" />
                <asp:BoundField DataField="IndependentRole" HeaderText="IndependentRole" SortExpression="IndependentRole" />
            </Columns>

            <EditRowStyle BackColor="Yellow"></EditRowStyle>

            <SelectedRowStyle BackColor="GreenYellow"></SelectedRowStyle>
        </asp:GridView>

Open in new window

Avatar of HainKurt
HainKurt
Flag of Canada image

do you have a link to see whats going on here?
when you open it in chrome and press F12, and type something, can you see any activity in Network tab in dev tools?
also try this on Line 4:

$("#<%=GridView1.ClientId%> .autosuggest")

and, Line 22

$(this).val(i.item.val);
or
e.target.value = i.item.val;
Avatar of Andrew

ASKER

User generated image
Avatar of Andrew

ASKER

With your suggested modifications, when I key a letter in the Country textbox in EditMode within the GridView I notice the box flicker - above is after I do that.
Avatar of Andrew

ASKER

 <script type="text/javascript">
        $(document)
            .ready(function () {
                $("#<%=GridView1.ClientId%> .autosuggest")
                    .autocomplete({
                        source: function (request, response) {
                            $.ajax({
                                type: "POST",
                                contentType: "application/json; charset=utf-8",
                                url: "../autocomplete.aspx/getCountries",
                                data: "{'prefixText':'" + $("#GridView1_Country").val() + "'}",
                                dataType: "json",
                                success: function (data) {
                                    response(data.d);
                                },
                                error: function (result) {
                                    alert("Error");
                                }
                            });
                        },
                        select: function (e, i) {
                            $(this).val(i.item.val);
                        },
                        change: function (e, ui) {
                            if (!(ui.item)) e.target.value = "";
                        },
                        minLength: 1
                    });

Open in new window

you should call to this "autocomplete.aspx/getCountries" if ajax is called...
Avatar of Andrew

ASKER

Should I change line 11?
yup, this does not make sense

$("#GridView1_Country").val()

>>> should be

$(this).val();
Avatar of Andrew

ASKER

Changed line 11 to this and it seems to be working now!  Thank you!

 data: "{'prefixText':'" + $("#<%=GridView1.ClientId%> .autosuggest").val() + "'}",
when you enter edit mode, and check the id of the text box, what do you see?
is it #GridView1_Country or something else... because this is generated dynamically...
unless you set ClientIDMode to static for that control, in that case id will be "Country" and make sure you dont have any other element on the page with that id... then we can use $("#Country") to select it or to add autocomplete functionality...
Avatar of Andrew

ASKER

ok I tried this:  

$(this).val();

and the textbox doesn't show autocomplete list, it just sits and spins the ajax loading .gif
above works if you have only one element on the page in the grid with that class...
I was trying to use id or "this" to make sure we are working with correct element all the time...
Avatar of Andrew

ASKER

		</tr><tr>
			<td><input type="button" value="Select" onclick="javascript:__doPostBack(&#39;GridView1&#39;,&#39;Select$10&#39;)" /></td><td style="white-space:nowrap;">
                        <input type="submit" name="GridView1$ctl12$btnEdit" value="Edit" id="GridView1_btnEdit_10" style="background-color:Yellow;" />
                        <input type="submit" name="GridView1$ctl12$btnDelete" value="Delete" onclick="return confirm(&#39;Are you sure you want to delete this record?&#39;);" id="GridView1_btnDelete_10" style="background-color:Red;" />
                    </td><td>11</td><td>meihann.lee@springer.com</td><td>meetingnanning</td><td>Mei Hann</td><td>Lee</td><td>Female</td><td>&nbsp;</td><td style="white-space:nowrap;">
                        <span id="GridView1_Country_10">Japan</span>
                    </td><td>&nbsp;</td><td>Chiyoda First Bldg. East, Nishi-Kanda 3-8-1, Chiyoda-ku, Tokyo 101-0065, Japan</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>+81-3-6831-7078</td><td>Akihoro Morimoto</td><td>meihannjp@yahoo.co.jp</td><td>Springer Japan KK</td><td>Dr.</td><td>&nbsp;</td><td>&nbsp;</td><td>9/8/2015 8:47:00 PM</td><td>&nbsp;</td><td>&nbsp;</td>
		</tr><tr style="background-color:WhiteSmoke;">
			<td><input type="button" value="Select" onclick="javascript:__doPostBack(&#39;GridView1&#39;,&#39;Select$11&#39;)" /></td><td style="white-space:nowrap;">
                        <input type="submit" name="GridView1$ctl13$btnEdit" value="Edit" id="GridView1_btnEdit_11" style="background-color:Yellow;" />
                        <input type="submit" name="GridView1$ctl13$btnDelete" value="Delete" onclick="return confirm(&#39;Are you sure you want to delete this record?&#39;);" id="GridView1_btnDelete_11" style="background-color:Red;" />
                    </td><td>12</td><td>tbngue@yahoo.com</td><td>ALGO2018</td><td>Thomas</td><td>NGUE BISSA</td><td>Male</td><td>&nbsp;</td><td style="white-space:nowrap;">
                        <span id="GridView1_Country_11">Cameroon</span>
                    </td><td>&nbsp;</td><td>P.O. BOX 15308</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>00237670506232</td><td>00237699917395</td><td>tbngue@yahoo.com</td><td>PIDMA</td><td>Engineer</td><td>&nbsp;</td><td>&nbsp;</td><td>11/24/2015 1:24:00 AM</td><td>&nbsp;</td><td>&nbsp;</td>
		</tr><tr>
			<td><input type="button" value="Select" onclick="javascript:__doPostBack(&#39;GridView1&#39;,&#39;Select$12&#39;)" /></td><td style="white-space:nowrap;">
                        <input type="submit" name="GridView1$ctl14$btnEdit" value="Edit" id="GridView1_btnEdit_12" style="background-color:Yellow;" />
                        <input type="submit" name="GridView1$ctl14$btnDelete" value="Delete" onclick="return confirm(&#39;Are you sure you want to delete this record?&#39;);" id="GridView1_btnDelete_12" style="background-color:Red;" />
                    </td><td>13</td><td>cyril.atung@nari.org.pg</td><td>chinaconference</td><td>Cyril</td><td>Atung</td><td>Male</td><td>&nbsp;</td><td style="white-space:nowrap;">
                        <span id="GridView1_Country_12">Papua New Guinea</span>
                    </td><td>&nbsp;</td><td>P O Box 1639 Lae 411, Morobe</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>00 675 4784000</td><td>Joyce Kolese</td><td>catkolese@gmail.com</td><td>Papua New Guinea National Agricultural Research Institute</td><td>Mr/Mrs/Miss</td><td>&nbsp;</td><td>&nbsp;</td><td>9/10/2015 3:46:00 AM</td><td>&nbsp;</td><td>&nbsp;</td>
		</tr><tr style="background-color:WhiteSmoke;">
			<td><input type="button" value="Select" onclick="javascript:__doPostBack(&#39;GridView1&#39;,&#39;Select$13&#39;)" /></td><td style="white-space:nowrap;">
                        <input type="submit" name="GridView1$ctl15$btnEdit" value="Edit" id="GridView1_btnEdit_13" style="background-color:Yellow;" />
                        <input type="submit" name="GridView1$ctl15$btnDelete" value="Delete" onclick="return confirm(&#39;Are you sure you want to delete this record?&#39;);" id="GridView1_btnDelete_13" style="background-color:Red;" />
                    </td><td>14</td><td>ndour09@gmail.com</td><td>123456M</td><td>NDOUR</td><td>MAMADOU</td><td>Male</td><td>&nbsp;</td><td style="white-space:nowrap;">
                        <span id="GridView1_Country_13">Senegal</span>
                    </td><td>&nbsp;</td><td>HANN MARISTE II</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>+221777786851</td><td>+221782916158</td><td>momochou2@gmail.com</td><td>www.ikt.com</td><td>Business</td><td>&nbsp;</td><td>&nbsp;</td><td>9/10/2015 10:25:00 AM</td><td>&nbsp;</td><td>&nbsp;</td>
		</tr><tr>

Open in new window

Avatar of Andrew

ASKER

Ok I understand.  So my Update would have updated every row instead of just the row I was actually editing?
this is not used to update

data: "{'prefixText':'" + $("#<%=GridView1.ClientId%> .autosuggest").val() + "'}",

but send the initial text and get the suggestion lists from server...

if you had multiple elements in grid with class=autosuggest, it would fail :)
if it works, then it means you have only one such element...
and thats why I tried "$(this).val()" here, but it did not work... should work, but dunno :)
Avatar of Andrew

ASKER

I changed line 11 back to this and it loads and I can select a country while in Edit mode.  

data: "{'prefixText':'" + $("#<%=GridView1.ClientId%> .autosuggest").val() + "'}",
after this line

source: function (request, response) {

Open in new window


put a

console.log($(this));
console.log($(this).val());

Open in new window


what does it print in console (chrome - F12)

maybe we should get it before and use it in ajax as

source: function (request, response) {
  var txt = $(this).val();
  console.log(txt);
                            $.ajax({
                                type: "POST",
                                contentType: "application/json; charset=utf-8",
                                url: "../autocomplete.aspx/getCountries",
                                data: "{'prefixText':'" + txt + "'}",
                                dataType: "json",
                                success: function (data) {
                                    response(data.d);
                                },
                                error: function (result) {
                                    alert("Error");
                                }
                            });
                        },

Open in new window

Avatar of Andrew

ASKER

But I understand now what you mean.  I am going to add the City autcomplete textbox now.  So you are saying it will fail, so we must figure something else out?
we can find a way to make all work eventually :)

as long as we understand whats going on, we can easily see what part fails and find a suitable solution that will work in all cases...
Avatar of Andrew

ASKER

This is the final gridview setup.  It now has Country and City with the .autocomplete class

 <%--<asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />--%>
                <asp:TemplateField  HeaderText="Country" ItemStyle-Wrap="False">
                    <EditItemTemplate>
                        <asp:TextBox ID="Country" runat="server" CssClass="autosuggest" Text='<%#Bind("Country")%>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Country" runat="server" Text='<%#Eval("Country")%>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField  HeaderText="City" ItemStyle-Wrap="False">
                    <EditItemTemplate>
                        <asp:TextBox ID="City" runat="server" CssClass="autosuggest" Text='<%#Bind("City")%>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="City" runat="server" Text='<%#Eval("City")%>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <%--<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />--%>

Open in new window

Avatar of Andrew

ASKER

and this just sits and spins...

<script type="text/javascript">
        $(document)
            .ready(function () {
                $("#<%=GridView1.ClientId%> .autosuggest")
                    .autocomplete({
                        source: function (request, response) {
                            $.ajax({
                                type: "POST",
                                contentType: "application/json; charset=utf-8",
                                url: "../autocomplete.aspx/getCountries",
                                data: "{'prefixText':'" + $(this).val() + "'}",
                                dataType: "json",
                                success: function (data) {
                                    response(data.d);
                                },
                                error: function (result) {
                                    alert("Error");
                                }
                            });
                        },
                        select: function (e, i) {
                            $(this).val(i.item.val);
                        },
                        change: function (e, ui) {
                            if (!(ui.item)) e.target.value = "";
                        },
                        minLength: 1
                    });

                $("#<%=GridView1.ClientId%> .autosuggest")
                    .autocomplete({
                        source: function (request, response) {
                            $.ajax({
                                type: "POST",
                                contentType: "application/json; charset=utf-8",
                                url: "../autocomplete.aspx/getCities",
                                data: "{'prefixText':'" + $(this).val() + "', 'countryText':'" + $(this).val() + "'}",
                                dataType: "json",
                                success: function (data) {
                                    response(data.d);
                                },
                                error: function (result) {
                                    alert("Error");
                                }
                            });
                        },
                        select: function (e, i) {
                            $(this).val(i.item.val);
                        },
                        change: function (e, ui) {
                            if (!(ui.item)) e.target.value = "";
                        },
                        minLength: 1
                    });
            });
    </script>

Open in new window

Avatar of Andrew

ASKER

So now we have:

<script type="text/javascript">
        $(document)
            .ready(function () {
                $("#<%=GridView1.ClientId%> .autosuggest")
                    .autocomplete({
                        source: function (request, response) {
                            var txt = $(this).val();
                            console.log(txt);
                            $.ajax({
                                type: "POST",
                                contentType: "application/json; charset=utf-8",
                                url: "../autocomplete.aspx/getCountries",
                                data: "{'prefixText':'" + txt + "'}",
                                dataType: "json",
                                success: function (data) {
                                    response(data.d);
                                },
                                error: function (result) {
                                    alert("Error");
                                }
                            });
                        },
                        select: function (e, i) {
                            $(this).val(i.item.val);
                        },
                        change: function (e, ui) {
                            if (!(ui.item)) e.target.value = "";
                        },
                        minLength: 1
                    });

                $("#<%=GridView1.ClientId%> .autosuggest")
                    .autocomplete({
                        source: function (request, response) {
                            var txt = $(this).val();
                            console.log(txt);
                            $.ajax({
                                type: "POST",
                                contentType: "application/json; charset=utf-8",
                                url: "../autocomplete.aspx/getCities",
                                data: "{'prefixText':'" + txt + "', 'countryText':'" + txt + "'}",
                                dataType: "json",
                                success: function (data) {
                                    response(data.d);
                                },
                                error: function (result) {
                                    alert("Error");
                                }
                            });
                        },
                        select: function (e, i) {
                            $(this).val(i.item.val);
                        },
                        change: function (e, ui) {
                            if (!(ui.item)) e.target.value = "";
                        },
                        minLength: 1
                    });
            });
    </script>

Open in new window


And get this error:

User generated image
put an alert or log and maybe you should call ajax when the text is more than equal to 3 chars

var txt = $(this).val();
console.log(txt);
if (txt.length>=3) $.ajax({...

Open in new window

and maybe you should use 2 different classes

asCountries
asCities

Open in new window


and use 2 different js

$(".asCountries").autocomplete({...});
$(".asCities").autocomplete({...});

Open in new window


bacause probably, in cities, you need to pass country value as well... and call different url/method
Avatar of Andrew

ASKER

This is the Autocomplete class currently used:

Imports System.Data.SqlClient
Imports System.Configuration

Partial Class Autocomplete
    Inherits System.Web.UI.Page

    <System.Web.Services.WebMethod()> _
    Public Shared Function getCountries(prefixText As String) As List(Of String)
	    Dim countries As New List(Of String)()

	    Using conn As New SqlConnection()
		    conn.ConnectionString = ConfigurationManager.ConnectionStrings("GCP21DBConnectionString").ConnectionString
		    Using cmd As New SqlCommand()
			    cmd.CommandText = "SELECT DISTINCT Country FROM [GCP21DBUser.Cities] WHERE " + "Country LIKE @SearchCountries + '%'"
			    cmd.Parameters.AddWithValue("@SearchCountries", prefixText)
			    cmd.Connection = conn
			    conn.Open()
			    Using dr As SqlDataReader = cmd.ExecuteReader()
				    While dr.Read()
					    countries.Add(dr("Country").ToString())
				    End While
			    End Using
			    conn.Close()
		    End Using
	    End Using
	    Return countries
    End Function

 <System.Web.Services.WebMethod()> _
    Public Shared Function getCities(prefixText As String, countryText As String) As List(Of String)
	    Dim Cities As New List(Of String)()

	    Using conn As New SqlConnection()
		    conn.ConnectionString = ConfigurationManager.ConnectionStrings("GCP21DBConnectionString").ConnectionString
		    Using cmd As New SqlCommand()
                cmd.CommandText = "SELECT DISTINCT City FROM [GCP21DBUser.Cities] WHERE " + "City LIKE @SearchCities + '%' and ((@searchCountry is null) or (Country = @searchCountry))"
                cmd.Parameters.AddWithValue("@SearchCities", prefixText)
                cmd.Parameters.AddWithValue("@searchCountry", countryText)
			    cmd.Connection = conn
			    conn.Open()
			    Using dr As SqlDataReader = cmd.ExecuteReader()
				    While dr.Read()
					    Cities.Add(dr("City").ToString())
				    End While
			    End Using
			    conn.Close()
		    End Using
	    End Using
	    Return Cities
    End Function

End Class

Open in new window

ok, as I guessed, you have 2 methods, so use different classes and use 2 different js function to add autocomplete...

$(".asCountries").autocomplete({...});
$(".asCities").autocomplete({...});

and in Cities, you should also pass country value...

url: "../autocomplete.aspx/getCities",
data: "{'prefixText':'" + txtCity + "', 'countryText':'"+ txtCountry + "'}",

Open in new window


and before ajax call, we need to get / set txtCity and txtCountry...

txtCountry = $(".asCountries").val();
txtCity = $(".asCities").val();

Open in new window

Avatar of Andrew

ASKER

Ok I understand the logic but am struggling with how to implement it...
ASKER CERTIFIED SOLUTION
Avatar of HainKurt
HainKurt
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Andrew

ASKER

Ok, thank you. I unfortunately cannot post the link publicly as it requires a login and I am unable to post any credentials publicly.  I will work on this overnight and post tomorrow morning.  Thanks again for your help so far today!
Avatar of Andrew

ASKER

Ok, I think I am close?  But still getting this error in the console:

User generated image
<script type="text/javascript">
	$(document)
		.ready(function () {
			$(".asCountries")
				.autocomplete({
					source: function (request, response) {
						var txt = $(this).val();
						console.log(txt);
						$.ajax({
							type: "POST",
							contentType: "application/json; charset=utf-8",
							url: "../autocomplete.aspx/getCountries",
							data: "{'prefixText':'" + $(".asCountries").val() + "'}",
							dataType: "json",
							success: function (data) {
								response(data.d);
							},
							error: function (result) {
								alert("Error");
							}
						});
					},
					select: function (e, i) {
						$(this).val(i.item.val);
					},
					change: function (e, ui) {
						if (!(ui.item)) e.target.value = "";
					},
					minLength: 1
				});
		});
</script>


<script type="text/javascript">
	$(document)
		.ready(function () {
			$(".asCities")
			   .autocomplete({
				   source: function (request, response) {
					   var txt = $(this).val();
					   console.log(txt);
					   $.ajax({
						   type: "POST",
						   contentType: "application/json; charset=utf-8",
						   url: "../autocomplete.aspx/getCities",
						   data: "{'prefixText':'" + $(".asCities").val() + "', 'countryText':'" + $(".asCountries").val() + "'}",
						   dataType: "json",
						   success: function (data) {
							   response(data.d);
						   },
						   error: function (result) {
							   alert("Error");
						   }
					   });
				   },
				   select: function (e, i) {
					   $(this).val(i.item.val);
				   },
				   change: function (e, ui) {
					   if (!(ui.item)) e.target.value = "";
				   },
				   minLength: 1
			   });
		});
</script>

Open in new window


<asp:TemplateField  HeaderText="Country" ItemStyle-Wrap="False">
	<EditItemTemplate>
		<asp:TextBox ID="asCountries" runat="server" CssClass="asCountries" Text='<%#Bind("Country")%>'></asp:TextBox>
	</EditItemTemplate>
	<ItemTemplate>
		<asp:Label ID="Countries" runat="server" Text='<%#Eval("Country")%>'></asp:Label>
	</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField  HeaderText="City" ItemStyle-Wrap="False">
	<EditItemTemplate>
		<asp:TextBox ID="asCities" runat="server" CssClass="asCities" Text='<%#Bind("City")%>'></asp:TextBox>
	</EditItemTemplate>
	<ItemTemplate>
		<asp:Label ID="Cities" runat="server" Text='<%#Eval("City")%>'></asp:Label>
	</ItemTemplate>
</asp:TemplateField>

Open in new window

Avatar of Andrew

ASKER

and these are the autcomplete methods:

<System.Web.Services.WebMethod()> _
Public Shared Function getCountries(prefixText As String) As List(Of String)
	Dim countries As New List(Of String)()

	Using conn As New SqlConnection()
		conn.ConnectionString = ConfigurationManager.ConnectionStrings("GCP21DBConnectionString").ConnectionString
		Using cmd As New SqlCommand()
			cmd.CommandText = "SELECT DISTINCT Country FROM [GCP21DBUser.Cities] WHERE " + "Country LIKE @SearchCountries + '%'"
			cmd.Parameters.AddWithValue("@SearchCountries", prefixText)
			cmd.Connection = conn
			conn.Open()
			Using dr As SqlDataReader = cmd.ExecuteReader()
				While dr.Read()
					countries.Add(dr("Country").ToString())
				End While
			End Using
			conn.Close()
		End Using
	End Using
	Return countries
End Function

<System.Web.Services.WebMethod()> _
Public Shared Function getCities(prefixText As String, countryText As String) As List(Of String)
	Dim Cities As New List(Of String)()

	Using conn As New SqlConnection()
		conn.ConnectionString = ConfigurationManager.ConnectionStrings("GCP21DBConnectionString").ConnectionString
		Using cmd As New SqlCommand()
			cmd.CommandText = "SELECT DISTINCT City FROM [GCP21DBUser.Cities] WHERE " + "City LIKE @SearchCities + '%' and ((@searchCountry is null) or (Country = @searchCountry))"
			cmd.Parameters.AddWithValue("@SearchCities", prefixText)
			cmd.Parameters.AddWithValue("@searchCountry", countryText)
			cmd.Connection = conn
			conn.Open()
			Using dr As SqlDataReader = cmd.ExecuteReader()
				While dr.Read()
					Cities.Add(dr("City").ToString())
				End While
			End Using
			conn.Close()
		End Using
	End Using
	Return Cities
End Function

Open in new window

data: "{'prefixText':'" + $(".asCountries").val() + "'}",

>>>

data: "{'prefixText':'" + txt + "'}",

Open in new window


thats why we used txt variable... and for cities

var txt = $(this).val();
var country = $(".asCountries").val();
					   console.log(txt+ " - " + country );
					   $.ajax({
						   type: "POST",
						   contentType: "application/json; charset=utf-8",
						   url: "../autocomplete.aspx/getCities",
						   data: "{'prefixText':'" + txt + "', 'countryText':'" + country + "'}",
						   dataType: "json",

Open in new window


and I dont see any issue for now...
you should debug now, open it with chrome, press F12, and check network to see whats going on
also, you can install fiddler and see what is requesting and what response you get from server...