最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - jquery autocomplete for multiple textboxes inside asp.net Gridview - Stack Overflow

programmeradmin1浏览0评论

I have asp Gridview that have at least 15 rows with textbox by default example

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 (here how I am generating 15 rows of a 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_Sqlmand = new SqlCommand("Select DISTINCT OtherService as txt1 from easy_tblOtherServiceMaster where OtherService like @SearchText + '%' ", obj_SqlConnection))
            {
                obj_SqlConnection.Open();
                obj_Sqlmand.Parameters.AddWithValue("@SearchText", txt1);
                SqlDataReader obj_result1 = obj_Sqlmand.ExecuteReader();
                while (obj_result1.Read())
                {
                    result.Add(obj_result1["txt1"].ToString().TrimEnd());
                }
            }
        }

        return result;
    }

I want to fill each textbox by jQuery autoplete.. for this I created a webservice and getting a value from jQuery.

How I am trying to achieve this task:

<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).autoplete({
                            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 %>").autoplete({
                          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> 

Now for example when I type "Engine Work" in TEXTBOX 1 and select the value which populated by jQuery autoplete("Engine Work") then second time when I type in other text box (TEXT BOX 2). It's only give me the "Engine Work" option to select.. which means after selecting any value (populated by jQuery autoplete) I can't select any other value in other text boxes.... Example:- (See Image Below)

as you see i type Genral Work but still it`s populating the Previous value "Engine Work" in jquery AutoComplete which i dont want

How to find the TextBox by CSS Class using jQuery????

Something like this (its only find TextBox id by using jQuery inside GridView but I need to find textbox by Css Class)

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

I have asp Gridview that have at least 15 rows with textbox by default example

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 (here how I am generating 15 rows of a 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_Sqlmand = new SqlCommand("Select DISTINCT OtherService as txt1 from easy_tblOtherServiceMaster where OtherService like @SearchText + '%' ", obj_SqlConnection))
            {
                obj_SqlConnection.Open();
                obj_Sqlmand.Parameters.AddWithValue("@SearchText", txt1);
                SqlDataReader obj_result1 = obj_Sqlmand.ExecuteReader();
                while (obj_result1.Read())
                {
                    result.Add(obj_result1["txt1"].ToString().TrimEnd());
                }
            }
        }

        return result;
    }

I want to fill each textbox by jQuery autoplete.. for this I created a webservice and getting a value from jQuery.

How I am trying to achieve this task:

<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).autoplete({
                            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 %>").autoplete({
                          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> 

Now for example when I type "Engine Work" in TEXTBOX 1 and select the value which populated by jQuery autoplete("Engine Work") then second time when I type in other text box (TEXT BOX 2). It's only give me the "Engine Work" option to select.. which means after selecting any value (populated by jQuery autoplete) I can't select any other value in other text boxes.... Example:- (See Image Below)

as you see i type Genral Work but still it`s populating the Previous value "Engine Work" in jquery AutoComplete which i dont want

How to find the TextBox by CSS Class using jQuery????

Something like this (its only find TextBox id by using jQuery inside GridView but I need to find textbox by Css Class)

var $arrT = $('#<%=gv_Others.ClientID %>').find('input:text[id$="txtEmp"]');
Share Improve this question edited Jun 5, 2014 at 14:59 Siddiq Baig asked Jun 5, 2014 at 13:26 Siddiq BaigSiddiq Baig 5862 gold badges17 silver badges37 bronze badges 1
  • Thanks for updating the question. Sometimes my eyes read "What's 1 + 1?" and my mind interprets it as "What's the capital of Nebraska?"... – Zach Commented Jun 5, 2014 at 15:01
Add a ment  | 

2 Answers 2

Reset to default 3

Change your script block to this:

$(document).ready(function() {
    // This selects all inputs inside the table with the txtE class and applies
    // the autoplete function to them
    $('table[id$="gv_Others"] input.txtE').autoplete({
        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
    });
});

Look at the data: in the ajax post - it's using request.term and I changed the selector.

The issue with your jquery is this line:

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

That will always return the first value of the array (the first textbox) so it's always submitting the first value to your webservice as the search text.

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./ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
        <script src="http://ajax.aspnetcdn./ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
        <link href="http://ajax.aspnetcdn./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]").autoplete({ source: 
                   "/Handlers/SearchDPN.ashx" });
            }
        </script>
发布评论

评论列表(0)

  1. 暂无评论