In this article I will explain how to implement JQuery UI autocomplete textbox with multiple words or values with comma separated or semi colon separated in asp.net.
In previous articles I explained JQuery autocomplete textbox with asp.net and JQuery autocomplete textbox with images in asp.net and many articles relating to JQuery. Now I will explain how to implement autocomplete textbox with multiple word selection in asp.net.
Column Name
|
Data Type
|
Allow Nulls
|
UserId
|
int(set
identity property=true)
|
No
|
UserName
|
varchar(50)
|
Yes
|
Location
|
nvarchar(max)
|
Yes
|
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"
runat="server">
<title>AutoComplete Box with jQuery</title>
<link href="css/ui-lightness/jquery-ui-1.8.21.custom.css" rel="stylesheet"
type="text/css"
/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
SearchText();
});
function SearchText() {
$("#txtSearch").autocomplete({
source: function(request,
response) {
$.ajax({
type: "POST",
contentType: "application/json;
charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'username':'"
+ extractLast(request.term) + "'}",
dataType: "json",
success: function(data)
{
response(data.d);
},
error: function(result)
{
alert("Error");
}
});
},
focus: function()
{
// prevent value inserted on
focus
return false;
},
select: function(event,
ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the
comma-and-space at the end
terms.push("");
this.value = terms.join(",
");
return false;
}
});
$("#txtSearch").bind("keydown", function(event)
{
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
}
</script>
</head>
<body>
<form id="form1"
runat="server">
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">Enter
UserName: </label>
<asp:TextBox ID="txtSearch"
runat="server"
Width="300px"></asp:TextBox>
</div>
</form>
</body>
</html>
|
$("#txtSearch").autocomplete({
source: function(request,
response) {
$.ajax({
type: "POST",
contentType: "application/json;
charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'username':'"
+ extractLast(request.term) + "'}",
dataType: "json",
success: function(data)
{
response(data.d);
},
error: function(result)
{
alert("Error");
}
});
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;
|
protected void
Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<string>
GetAutoCompleteData(string username)
{
List<string>
result = new List<string>();
using (SqlConnection
con = new SqlConnection("Data Source=SureshDasari;Integrated
Security=true;Initial Catalog=MySampleDB"))
{
using (SqlCommand
cmd = new SqlCommand("select DISTINCT UserName from UserInformation
where UserName LIKE '%'+@SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("@SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["UserName"].ToString());
}
return result;
}
}
}
|
Imports System.Collections.Generic
Imports System.Data.SqlClient
Imports System.Web.Services
Partial Class
Default
Inherits System.Web.UI.Page
Protected Sub
Page_Load(ByVal sender As Object, ByVal e As
EventArgs) Handles Me.Load
End Sub
<WebMethod()> _
Public Shared Function GetAutoCompleteData(ByVal username As String) As List(Of String)
Dim result As New List(Of String)()
Using con As New SqlConnection("Data
Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
Using cmd As New SqlCommand("select
DISTINCT UserName from UserInformation where UserName LIKE
'%'+@SearchText+'%'", con)
con.Open()
cmd.Parameters.AddWithValue("@SearchText", username)
Dim dr As SqlDataReader =
cmd.ExecuteReader()
While dr.Read()
result.Add(dr("UserName").ToString())
End While
Return result
End Using
End Using
End Function
End Class
|
|
|
|
If you enjoyed this post, please support the blog below. It's FREE! Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email. |
|||
Subscribe by RSS
Subscribe by Email
|
|||
|
|
|


Subscribe by RSS
Subscribe by Email
27 comments :
Dear Friend,
I have created a web service and hosted on the server like http://119.82.71.78:903/MessageBoardService.asmx
and i called it on another project but i am not able to access this web sevrice . what could be the reason ?
MessageBoardService.asmx.cs
//Code
using System;
using System.Collections;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Web.Services;
using System.Web.Script.Services;
///
/// Summary description for MessageBoardService
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class MessageBoardService : System.Web.Services.WebService
{
public MessageBoardService()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List GetAutoCompleteData(string username)
{
List result = new List();
if (!string.IsNullOrEmpty(username))
{
using (SqlConnection con = new SqlConnection("Data Source=MySerevr;Max Pool Size=600; Initial Catalog=MyMBDB;Persist Security Info=True;User ID=sa;Password=saa"))
{
using (SqlCommand cmd = new SqlCommand("select MemberFullName+'<'+UserID+'>' As username from View_MemberInformation where MemberFullName LIKE'%'+@SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("@SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["UserName"].ToString());
}
//return result;
}
}
}
return result;
}
}
and in aspx page // This is another projects.
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://119.82.71.78:903/MessageBoardService.asmx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
//alert("Error");
alert(result.status)
}
});
}
});
}
But its working fine where webservice is hosted.
Thanks
Alok Kumar sharma
alokmca1984@gmail.com
India
dfgadgaa
Hi Suresh,
Thanks for sharing this article.
There is an error in sample code(default.aspx).
The below url is not working for sample code.
url: "Default.aspx/GetAutoCompleteData",
The url should be
url: "AutoCompletewithMultipleSelection.aspx/GetAutoCompleteData",
@Milind,
There is no error in code Default.aspx is the page name of my application if you use another pagename then you need to change url: "PageName/MethodName"
There is an error in downloaded code.
The page name of application is AutoCompletewithMultipleSelection.aspx.
code :
url: "Default.aspx/GetAutoCompleteData",
@Milind,
that is not problem or error in post. Please give your application pagename that's enough
there is no error on the article.
there is problem on downloadable sample code.
Thanks Milind...
i updated downloadable sample also...
No problem. :-)
nice but i mnot able to use it on my master page :(
any solution?
its working perfectly on simple / single page
but on the page where master page is included i m not able to use it.
plz give me solution for tat with full code thanks for great article
it will work on master pages also i hope you guys are not adding the jquery refrences in master that's the reason that auto complete not working in master. Please check it once...
If we want autocomplete search for two textboxes in the same aspx page, which will fetch data from two different tables. Then what will be the code for that?
Hi Suresh
Thanks, this is great and works perfectly and easily. However have you explored formating the input so that it is formatted as a label e.g as the example on this page textextjs dot com/?
Re: 13
it does not work on a child page of a master page. all the references are correct and also the url to the web service, case of json etc... i am using eact same code on a page that is not a child page of master page and it works... any ideas? thanks.
Re: 13 and 16
It does work on child page of master page however reference the client id of the textbox i.e "#<%=txtSearch.ClientID%>"
Awesome
Hi Suresh,
Nice work! I need when you select "Mahendra" so it would not be next time in List of search.
Can you help me into this.
Thanks in advance.
Great thanks again.
- Ankur Dalal
Suresh, Naku koncham JQuery and Javascript help kavali ..some thing related to Autocomplete and JS Keydown event ... requirement chala typical vundi..asalu logic idea ne ravatam ledu...ma native kuda tenali ne...pls help me..ne contact number cheppu ...my contact is 8861319319
I using jquery tokeninput, i want you give me example ASP.NET server-side script for generating
responses suitable for use with jquery-tokeninput
Thanks!!!
Hi Suresh. Thank you for Sharing this . i have a query in my ASpx page am having two Auto Complete textboxes . how can i fire only one event at a time.
It is so great article and easily understandable...I am new to Jquery.So I need one more thing suresh..How to get all the UserId of the all selected Username??I saw one of your article to select one item and its id.In this case how can I get multiple ids.Can you help me into this.
Thanks in advance.
Thanks again.
Hi, i checked this. is it working in user Control ?
can u tell me please
Suresh ,
after deploying in IIS
SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
will works perfectly
but
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
won't work , it will give an alert with "error".
Is there any thing like we have to hard code this connection string in code file .
please check and leave a reply
Thanks
However nice implementation
Works fine. Thanks
just one correction: this
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) { event.preventDefault(); }
with this.
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("ui-autocomplete").menu.active) { event.preventDefault(); }
there is multiple spaces in between last charecter of name and comma (,), how to avoid it?