JQuery autocomplete function within Radgrid

1 Answer 171 Views
Grid
Richard
Top achievements
Rank 1
Richard asked on 22 Jun 2023, 11:28 AM | edited on 22 Jun 2023, 11:30 AM

Hello

I have an @Mention function that works within a normal aspx textarea.  It autocompletes names when entering the @ symbol and start typing the name.  Do you know how I can get this to work within Radgrid.  In the code below I need it specifically within the "Mat" column.

Here is the JavaScript:

        ////@mention function

        $(document).ready(function () {
            var availableTags = []; // You will fill this with data from server side

            function split(val) {
                return val.split(/@\s*/);
            }

            function extractLast(term) {
                return split(term).pop();
            }

            $(".mention")
                .on("keydown", function (event) {
                    if (event.keyCode === $.ui.keyCode.TAB && $(this).autocomplete("instance").menu.active) {
                        event.preventDefault();
                    }
                })
                .autocomplete({
                    minLength: 2,
                    source: function (request, response) {
                        var term = extractLast(request.term);
                        if (term.length >= 1) {
                            // ajax call to the server-side method
                            $.ajax({
                                url: './ProjectTracker.aspx/GetUsers',
                                method: 'POST',
                                contentType: 'application/json',
                                data: JSON.stringify({ 'prefix': term }),
                                success: function (data) {
                                    response(data.d);
                                }
                            });
                        }
                    },
                    focus: function () {
                        return false;
                    },

                    select: function (event, ui) {
                        var terms = split(this.value);
                        // remove the term before '@' symbol
                        terms.pop();
                        // add the selected item
                        terms.push(ui.item.value);
                        // join the terms with '@' and append space, instead of '@' at the end
                        this.value = terms.join("@") + ' ';
                        return false;
                    }
                });
        });

        $(".mention").autocomplete({
            // ... other options ...
            open: function () {
                $(this).autocomplete('widget').css('width', $(this).outerWidth());
            }
        });

Here is the Radgrid:

                     <telerik:RadGrid RenderMode="Lightweight" OnPreRender="Slippage_PreRender" runat="server" ID="Slippage" AutoGenerateColumns="false"
                        OnNeedDataSource="Slippage_NeedDataSource" OnUpdateCommand="Slippage_UpdateCommand" OnItemDataBound="Slippage_ItemDataBound"
                        OnItemCreated="Slippage_ItemCreated" OnDeleteCommand="Slippage_DeleteCommand" Skin="WebBlue"
                        OnInsertCommand="Slippage_InsertCommand" ShowHeadersWhenNoRecords="true">
                        <MasterTableView AutoGenerateColumns="False" EditMode="InPlace" DataKeyNames="ID" InsertItemDisplay="Bottom" CommandItemDisplay="Bottom" EnableHeaderContextMenu="false" ShowHeadersWhenNoRecords="true">
                           <PagerStyle Mode="NextPrevAndNumeric" PageSizeLabelText="Page Size: " PageSizes="300" />
                           <Columns>
                              <telerik:GridEditCommandColumn HeaderStyle-Width="20" ItemStyle-Width="20" UniqueName="start">
                              </telerik:GridEditCommandColumn>
                              <telerik:GridBoundColumn  DataField="Mat" DefaultInsertValue="" HeaderText="Slippage"  
                                 SortExpression="Mat" UniqueName="Mat" ItemStyle-CssClass="maximize">
                              </telerik:GridBoundColumn>
                              <telerik:GridCheckBoxColumn UniqueName="risk" HeaderText="At Risk"   ItemStyle-HorizontalAlign="Center"  HeaderStyle-HorizontalAlign="Center" HeaderStyle-Width="100px" DataField="risk" >
                              </telerik:GridCheckBoxColumn>
                              <telerik:GridButtonColumn Text="Delete" HeaderStyle-Width="50" ItemStyle-Width="50" CommandName="Delete" UniqueName="Delete"/>
                           </Columns>
                        </MasterTableView>
                        <ClientSettings AllowDragToGroup="false" AllowColumnsReorder="false">
                           <Resizing AllowColumnResize="false"></Resizing>
                        </ClientSettings>
                     </telerik:RadGrid>
                     <div style="clear: both"></div>
                     <br />
                  </div>
               </div>
            </div>

Here is the code for GetUsers:

        [System.Web.Services.WebMethod]
        public static List<string> GetUsers(string prefix)
        {
            List<string> users = new List<string>();
            // Query your database here based on the prefix and fill the 'users' list
            // This is a simple demonstration with static data
            List<string> allUsers = new List<string> { "John", "Alpha Bravo", "James", "Zack Smith", "Joy" };

            // For simplicity we are just doing a StartsWith. You might need to use a 'LIKE' query in SQL or equivalent
            users = allUsers.Where(u => u.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase)).ToList();

            return users;
        }

 

Here is a normal textarea that works with the function:

             <textarea class="mention" id="textArea" rows="4" cols="50"></textarea>

 

I've added these into the aspx  page:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

1 Answer, 1 is accepted

Sort by
0
Attila Antal
Telerik team
answered on 27 Jun 2023, 08:42 AM

Hi Richard,

You can access the elements of Telerik Controls as you would normally do with any elements. If you inspect the rendered HTML elements of the Grid you will understand the current rendered structure and you can create a selector that will target the input element you like.

One of the events you can use for this purpose is the GridCreated event.

Example:

<telerik:RadGrid ID="RadGrid1" runat="server" OnNeedDataSource="RadGrid1_NeedDataSource">
    <MasterTableView>
        <Columns>
            <telerik:GridBoundColumn DataField="Mat" DefaultInsertValue="" HeaderText="Slippage"
                SortExpression="Mat" UniqueName="Mat" ItemStyle-CssClass="maximize">
            </telerik:GridBoundColumn>
        </Columns>
    </MasterTableView>
    <ClientSettings>
        <ClientEvents OnGridCreated="OnGridCreated" />
    </ClientSettings>
</telerik:RadGrid>

<script>
    function OnGridCreated(sender, args) {
        var grid = sender;

        var $matInputElement = $(grid.get_element()).find('input[id$=TB_Mat]');

        $matInputElement.on("keydown", function (event) {
            if (event.keyCode === $.ui.keyCode.TAB && $(this).autocomplete("instance").menu.active) {
                event.preventDefault();
            }
        }).autocomplete({
            // ...
        });
    }
</script>

 

You may also attach the event to the document directly, but filter for the Input element from the Mat column

<script>
    (function () {
        $(document).on("keydown", '.RadGrid .rgMasterTable .rgEditForm input[id$=TB_Mat]', function (event) {
            if (event.keyCode === $.ui.keyCode.TAB && $(this).autocomplete("instance").menu.active) {
                event.preventDefault();
            }
        }).autocomplete({
            // ...
        });
    })()
</script>

 

Note: For the sake of security we recommend using the query embedded in the Telerik Assemblies, however, if you prefer to include an external jQuery, be sure the disable the embedded one from Telerik, see Including external jQuery

 

Regards,
Attila Antal
Progress Telerik

Heads up! Telerik UI for ASP.NET AJAX versions for .NET 3.5 and 4.0 are retired. Progress will continue shipping assemblies compatible with .NET 4.5 and later. See whether this affects your apps in this article.
Tags
Grid
Asked by
Richard
Top achievements
Rank 1
Answers by
Attila Antal
Telerik team
Share this question
or