对于asp.net Gridview中的多个文本框,jquery自动完成

时间:2014-06-05 13:26:38

标签: c# javascript jquery asp.net gridview

我的asp.net Gridview默认情况下至少有15行文本框

enter image description here

ASPX

<asp:GridView ID="gv_Others" runat="server" AutoGenerateColumns="false" CssClass="gvothers">
                    <Columns>
                    <asp:TemplateField >                        
                        <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                        <ItemTemplate >                     
                            <asp:TextBox ID="txtEmp" runat="server" Width=100% Height=22px CssClass="txtE"></asp:TextBox>
                        </ItemTemplate>
                    </asp:TemplateField>
                    </Columns>
                </asp:GridView>

aspx.cs(这里我是如何生成15行的GridView

private void SetInitialRowsofOthers()
    {
        var list = new List<string>();

        for (int i = 0; i < 16; i++)
        {
            list.Add(string.Empty);
        }
        gv_Others.DataSource = list;
        gv_Others.DataBind();
        gv_Others.HeaderRow.Visible = false;

     }

WevService.axms

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<string> GetotherServices(string txt1)
    {
        // your code to query the database goes here
        List<string> result = new List<string>();
        string QueryString = System.Configuration.ConfigurationManager.ConnectionStrings["autoDBConn"].ToString();

        using (SqlConnection obj_SqlConnection = new SqlConnection(QueryString))
        {
            using (SqlCommand obj_Sqlcommand = new SqlCommand("Select DISTINCT OtherService as txt1 from easy_tblOtherServiceMaster where OtherService like @SearchText + '%' ", obj_SqlConnection))
            {
                obj_SqlConnection.Open();
                obj_Sqlcommand.Parameters.AddWithValue("@SearchText", txt1);
                SqlDataReader obj_result1 = obj_Sqlcommand.ExecuteReader();
                while (obj_result1.Read())
                {
                    result.Add(obj_result1["txt1"].ToString().TrimEnd());
                }
            }
        }

        return result;
    }

我想用jQuery autocomplete填充每个文本框..为此,我创建了一个web服务并从jQuery获取值。

我如何努力完成这项任务:

<script src="js/jquery-1.8.1.js" type="text/javascript"></script>
            <script type="text/javascript">
                $(document).ready(function() {
                    SearchText();
                    function SearchText() {
                        var $arrT = $('#<%=gv_Others.ClientID %>').find('input:text[id$="txtEmp"]');
                        $($arrT).autocomplete({
                            source: function(request, response) {
                                $.ajax({
                                url: "WebService.asmx/GetotherServices",
                                    type: "POST",
                                    dataType: "json",
                                    contentType: "application/json; charset=utf-8",
                                    data: "{ 'txt1' : '" + $($arrT).val() + "'}",
                                    dataFilter: function(data) { return data; },
                                    success: function(data) {
                                        response($.map(data.d, function(item) {
                                            return {
                                                label: item,
                                                value: item
                                            }
                                        }))
                                        //debugger;
                                    },
                                    error: function(result) {
                                        alert("Error");
                                    }
                                });
                            },
                            minLength: 1,
                            delay: 1000
                        });
                    }
                });
        </script>

          <script type="text/javascript">
              $(document).ready(function() {

                  SearchText();

                  function SearchText() {
                      $("#<%=Txt_RegNo.ClientID %>").autocomplete({
                          source: function(request, response) {
                              $.ajax({
                              url: "WebService.asmx/GetAutoCompleteData",
                                  type: "POST",
                                  dataType: "json",
                                  contentType: "application/json; charset=utf-8",
                                  data: "{ 'txt' : '" + $("#<%=Txt_RegNo.ClientID %>").val() + "'}",
                                  dataFilter: function(data) { return data; },
                                  success: function(data) {
                                      response($.map(data.d, function(item) {
                                          return {
                                              label: item,
                                              value: item
                                          }
                                      }))
                                      //debugger;
                                  },
                                  error: function(result) {
                                      alert("Error");
                                  }
                              });
                          },
                          minLength: 1,
                          delay: 1000
                      });
                  }
              });
        </script>

            <script type="text/javascript">
                $(function() {  
                    $('input:text:first').focus();
                    var $inp = $('input:text');
                    $inp.bind('keydown', function(e) {
                        //var key = (e.keyCode ? e.keyCode : e.charCode);
                        var key = e.which;
                        if (key == 13) {
                            e.preventDefault();
                            var nxtIdx = $inp.index(this) + 1;
                            $(":input:text:eq(" + nxtIdx + ")").focus();
                        }
                    });
                });
                </script>
            <script type="text/javascript">
                function Load_OtherService() {
                    var hv = $('input[id$=hdnOthers]');
                    var $arrT = $('#<%=gv_Others.ClientID %>').find('input:text[id$="txtEmp"]');  
                    var hv1 = "" + hv.val();
                    var va = hv1.split(',');
                    for (var j = 0; j < va.length; j++) {
                        var $txt = $arrT[j];
                        $($txt).val(va[j]);
                    }                          
                }
            </script> 

现在例如当我在TEXTBOX 1中键入“Engine Work”并选择由jQuery autocomplete填充的值(“Engine Work”)时,我第二次输入其他文本框(TEXT BOX 2) 。它只给我选择“引擎工作”选项..这意味着在选择任何值(由jQuery autocomplete填充)后,我无法在其他文本框中选择任何其他值.... 示例: - (见下图)

enter image description here

如你所见,我输入Genral Work,但它仍然填充了我不想要的jquery AutoComplete中的Previous值“Engine Work”

如何使用jQuery ????

通过CSS类查找TextBox

像这样的东西(它只在GridView里面使用jQuery找到TextBox id,但我需要通过Css Class找到文本框)

var $arrT = $('#<%=gv_Others.ClientID %>').find('input:text[id$="txtEmp"]');

2 个答案:

答案 0 :(得分:3)

将脚本块更改为:

$(document).ready(function() {
    // This selects all inputs inside the table with the txtE class and applies
    // the autocomplete function to them
    $('table[id$="gv_Others"] input.txtE').autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "WebService.asmx/GetAutoCompleteData",
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: "{ 'txt1' : '" + request.term + "'}", 
                dataFilter: function(data) { return data; },
                success: function(data) {
                    response($.map(data.d, function(item) {
                        return {
                            label: item,
                            value: item
                        }
                    }))
                    //debugger;
                },
                error: function(result) {
                    alert("Error");
                }
            });
        },
        minLength: 1,
        delay: 1000
    });
});

使用data:查看ajax帖子中的request.term - 我更改了选择器。

你的jquery的问题是这一行:

data: "{ 'txt1' : '" + $($arrT).val() + "'}",

这将始终返回数组的第一个值(第一个文本框),因此它始终将第一个值作为搜索文本提交给您的Web服务。

答案 1 :(得分:0)

using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace PlatForm_RollUp
{
    /// <summary>
    /// Summary description for SearchDPN
    /// </summary>
    public class SearchDPN : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string prefixText = context.Request.QueryString["term"];
            if (string.IsNullOrEmpty(prefixText)) { prefixText = "NA"; }
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = ConfigurationManager
                        .ConnectionStrings["PPN_ConnectionString"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "select DPN_Key, DPN, Item_Desc from Customer.DIM.PPN WHERE " +
                        "DPN like @SearchText+'%'";
                    cmd.Parameters.AddWithValue("@SearchText", prefixText);
                    cmd.Connection = conn;
                    //StringBuilder sb = new StringBuilder();
                    List<string> _dpn = new List<string>();
                    conn.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            //sb.Append(string.Format("{0} - {1}", sdr["DPN"], sdr["Item_Desc"], Environment.NewLine));
                            _dpn.Add(sdr["DPN"].ToString() +" - " +sdr["Item_Desc"].ToString());
                        }
                    }
                    conn.Close();
                    context.Response.Write(new JavaScriptSerializer().Serialize(_dpn));
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}


***************************
 <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
        <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
        <link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" rel="Stylesheet" type="text/css" />      
         <script type="text/javascript">
            $(function () {
                initializer();
            });
            var prmInstance = Sys.WebForms.PageRequestManager.getInstance();
            prmInstance.add_endRequest(function () {
                //you need to re-bind your jquery events here
                initializer();
            });
            function initializer() {

                $("[id*=txtDPN]").autocomplete({ source: 
                   "/Handlers/SearchDPN.ashx" });
            }
        </script>