使用JQuery autocomplete 一次完成多個欄位填寫
假設我有三個欄位,分別是姓名、電話、住址。我想在輸入姓名的時候用autocomplete去撈出資料庫中的姓名,選好後三個欄位都幫我填入所屬該姓名的資料。
在web service部分我把要回傳的值用';'來區別。
前端網頁處理
在web service部分我把要回傳的值用';'來區別。
<%@ WebHandler Language="VB" Class="TeacherCo" %>
Imports System
Imports System.Web
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Text
Public Class TeacherCo : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim prefixText As String = context.Request.QueryString("q")
Dim conn As SqlConnection = New SqlConnection
conn.ConnectionString = ConfigurationManager.ConnectionStrings("AAA").ConnectionString
Dim cmd As SqlCommand = New SqlCommand
cmd.CommandText = ("SELECT 姓名,電話,住址 FROM 資料表 WHERE " & _
"姓名 like @SearchText + '%'")
cmd.Parameters.AddWithValue("@SearchText", prefixText)
cmd.Connection = conn
Dim sb As StringBuilder = New StringBuilder
conn.Open()
Dim sdr As SqlDataReader = cmd.ExecuteReader
While sdr.Read
sb.Append(sdr(0) & ";" & sdr(1) & ";" sdr(2)).Append(Environment.NewLine)
End While
conn.Close()
context.Response.Write(sb.ToString)
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
前端網頁處理
$(document).ready(function() {
//auto complete
$("#姓名").autocomplete('TeacherCo.ashx', {
scrollHeight: 220,
formatItem: function(data, i, total) {
var StrAndNum = data[0].split(';');
return StrAndNum[0];
},
formatResult: function(data) {
var StrAndNum = data[0].split(';');
return StrAndNum[0];
}
});
$("#姓名").result(function(event, data, formatted){
var StrAndNum = data[0].split(';');
if (StrAndNum[1] != null){
$("#電話").val(StrAndNum[1]); $("#住址").val(StrAndNum[2]);
}else{
$("#電話").val('');$("#住址").val('');
}
});
0 comments: