Solved

Use jQuery to filter a List in a GridView

Posted on 2013-01-17
16
1,336 Views
Last Modified: 2013-06-08
I need to implement the autofiltering of the GridView to the text input into a textbox. I have not been successful getting the <asp:GridView> to filter from a textbox. I do not understand why my GridView is not filtering.

I have been experimenting with 2 different jQuery scripts I found online, but neither will work. I expect I have mis-coded something. Here are the two different scripts (I am NOT using both script simultaneously. I comment one or the other out):
<script type="text/javascript">
     $(document).ready(function () {
         //
         // Client Side Search (Autocomplete)
         // Get the search Key from the TextBox
         // Iterate through the 1st Column.
         // td:nth-child(1) - Filters only the 1st Column
         // If there is a match show the row [$(this).parent() gives the Row]
         // Else hide the row [$(this).parent() gives the Row]
         $('#txtID').keyup(function (event) {
             var searchKey = $(this).val().toLowerCase();
             $("#grdClient tr td:nth-child(1)").each(function () {
                 var cellText = $(this).text().toLowerCase();
                 if (cellText.indexOf(searchKey) >= 0) {
                     $(this).parent().show();
                 }
                 else {
                     $(this).parent().hide();
                 }
             });
         });
     });
</script>   

Open in new window

and then
<script type="text/javascript" language="javascript">
function SetupFilter(textboxID, gridID, columnName) {
    $('#' + textboxID).keyup(function () {
        var index;
        var text = $("#" + textboxID).val();
 
        $('#' + gridID + ' tbody tr').each(function () {
            $(this).children('th').each(function () {
                if ($(this).html() == columnName)
                    index = $(this).index();
            });
 
            $(this).children('td').each(function () {
                if ($(this).index() == index) {
                    var tdText = $(this).children(0).html() == null ? $(this).html() : $(this).children(0).html();
 
                    if (tdText.indexOf(text, 0) > -1) {
                        $(this).closest('tr').show();
                    } else {
                        $(this).closest('tr').hide();
                    }
                };
            });
        });
    });
};


$(function () { SetupFilter("txtID", "grdClient", "Name"); });
</script>

Open in new window

and the SharePoint 2010 controls are listed here
<asp:TextBox runat="server" type="text" name="Search" id="txtID" ClientIDMode="Static"   />
<asp:GridView ID="grdClient" runat="server" AutoGenerateColumns="false" DataSourceID="dsClient" ClientIDMode="Static">
    <Columns>
        <asp:BoundField DataField="clientname" HeaderText="Name" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:HyperLink ID="searchresults" runat="server" Text='<%#Eval("clientid").ToString() %>' NavigateUrl='<%# "http://abcdev/client/SitePages/abcdefault.aspx?clientid="+Eval("clientid").ToString() %>'></asp:HyperLink>
            </ItemTemplate>
        </asp:TemplateField>       
    </Columns>
</asp:GridView>

Open in new window

I omitted the datasource code from the above markup as it wasn't directly relative. I am referencing a jQuery library in the master page version "1.7.2.js" I am stumped as to why the GridView is not filtering.
I have also verified that my jQuery script library is loading by using the IE Dev toolbar and locating my script library tag. Additionally I have performed a sanity check and run a code sample into the script editor window of IE Dev Toolbar as illustrated http://www.codeproject.com/Articles/250504/Using-jQuery-with-Sharepoint-2010

So, I know jQuery works, but why doesn't this specific code against my GridView?
0
Comment
Question by:vpit
  • 10
  • 3
  • 2
  • +1
16 Comments
 

Author Comment

by:vpit
Comment Utility
Ok, so now I am even more miffed ... I added some test jQuery code to may page to change the color of a label when the page loads and it doesn't work. I am pretty sure that the code is written correctly, but could someone check and help determine why the jQuery is not functioning in the page?

<script type="text/javascript" language="javascript">
    $(document).ready(function () {
        $("#lblLabel").css("color", "red");
    });
</script>

Open in new window


which is targeting this label control below

<asp:Label runat="server" ID="lblLabel" Text="Filter: " />

Open in new window


Any ideas?
0
 
LVL 41

Expert Comment

by:guru_sami
Comment Utility
1: For the grid filtering, add some alerts to see how for is the code running..
2: For label, make sure your lblLabel's id isn't changed by asp.net else it won't be accessible via #lblLabel in jquery.
0
 

Author Comment

by:vpit
Comment Utility
guru_sami,
Something is wrong ... I changed the jQuery to the following to test the most basic of jQuery functions. And I get nothing!
<script type="text/javascript" language="javascript">
    $(document).ready(function () {
        alert('Hello World');
    });
</script>

Open in new window

No alert box is displayed at all. Something is blocking the execution of the code ... wouldn't you think?
0
 
LVL 44

Expert Comment

by:Rainer Jeschor
Comment Utility
Hi,
please follow these two rules:
1. Use jQuery in non-conflict mode
Meaning use jQuery(document) instead of $(document
2. Use the existing load wrapper
Use _spBodyOnLoadFunctionNames.push("YourFunctionName") instead of doc.ready
See here
http://www.stephanrocks.com/2011/10/05/_spbodyonloadfunctionnames-in-sharepoint-vs-jquerys-document-ready/

Additionally check if jQuery is loaded:
alert(jQuery);

If you get undefined, then no jQuery library is loaded.
Additionally verify that there is no Javascript error before your code.

HTH
Rainer
0
 
LVL 15

Expert Comment

by:colly92002
Comment Utility
You can also use the developer tools in IE8 and later to see what scripts are loaded in a page.
0
 

Author Comment

by:vpit
Comment Utility
Ok, if I start using the jquery.noConflict() against, say 10 different javascript files already in-place, how do I go about implementing it?
screenshot of jquery namesIf I have the jquery files as listed above, do I have to go into each separate file and change all the references around? Or can I make a more global change in the Master Page?

Would this work by placing this into my SharePoint master page?
<script type="text/javascript" src="/_layouts/styles/branding/js/jquery-1.7.2.js"></script>
    <script type="text/javascript">var jq172 = $.noConflict(true);</script>
    <script type="text/javascript" src="/_layouts/styles/branding/js/jquery-1.8.3.js"></script>
    <script type="text/javascript">var jq183 = $.noConflict(true);</script>
    <script type="text/javascript" src="/_layouts/styles/branding/js/jquery-1.8.3-vsdoc.js"></script>
    <!-- jQuery Rounded Corners javascript controls -->
    <script type="text/javascript" src="/_layouts/styles/branding/js/jquery-ui-1.8.23.custom.min.js"></script> 
    <script type="text/javascript">var jqui1823min = $.noConflict(true);</script>
    <script type="text/javascript" src="/_layouts/styles/branding/js/jquery-ui-1.8.24.custom.min.js"></script>
    <script type="text/javascript">var jqui1824min = $.noConflict(true);</script>

Open in new window

0
 
LVL 44

Expert Comment

by:Rainer Jeschor
Comment Utility
Hi,
I do not think so (that you will have to modify each file).
I am not sure (have not yet run into this issue), but why do you want to load two different versions of jQuery and jQuery UI?
The latest version of each should be enough.

HTH
Rainer
0
 
LVL 15

Expert Comment

by:colly92002
Comment Utility
I include jQuery in masterpages using a scriptmanager object at the top of the body element, like this:
<body scroll="no" onload="if (typeof(_spBodyOnLoadWrapper) != 'undefined') _spBodyOnLoadWrapper();" class="v4master">
  <form runat="server" onsubmit="if (typeof(_spFormOnSubmitWrapper) != 'undefined') {return _spFormOnSubmitWrapper();} else {return true;}">
  <asp:ScriptManager id="ScriptManager" runat="server" EnablePageMethods="false" EnablePartialRendering="true" EnableScriptGlobalization="false" EnableScriptLocalization="true" >
  <Scripts>
	<asp:ScriptReference Path="<% $SPUrl:~sitecollection/Style%20Library/CESA/js/jquery-1.7.1.min.js%>"  runat="server"></asp:ScriptReference> 
        <asp:ScriptReference Path="<% $SPUrl:~sitecollection/Style%20Library/CESA/js/RenameILikeIt.js%>" runat="server"></asp:ScriptReference> 
        <asp:ScriptReference Path="<% $SPUrl:~sitecollection/Style%20Library/CESA/js/CESASecurity.js%>" runat="server"></asp:ScriptReference> 
	</Scripts> 
  </asp:ScriptManager>

Open in new window

(I've included the body and form elelemtn just to show you the relative position of thsi script manager in my masterpage)
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:vpit
Comment Utility
I have placed the jQuery files into the ScriptManager tag, however, I am getting an error in Visual Studio stating that ScriptManager is not recognized or a web.config is missing. However, I have a reference in the web.config as shown below, both in my local Foundation box and on the development server ...
<compilation batch="false" debug="true" optimizeCompilations="true">
      <assemblies>
        <add assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
       <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
		<add assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
        <add assembly="Microsoft.SharePoint.Search, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
      </assemblies>

Open in new window


As far as the jQuery.noConflict is concerned, I have not made much headway. I am still confused on how to edit all my external files. I researched the topic more and saw that by  adding
$ = jQuery.noConflict();

Open in new window

to each and every external jQuery file will fix the noConflict problem? I have read that if this code is added AND then find/replace every instance of the "$" with the text "jquery" in each separate external file then it should work. Would it?
If that would be the case, where would I place the the noConflict variable declaration? For example, I have open up my jquery-1.7.2.js file and see the following lines of code near the top ... where would be the best place to write this new code?
(function( window, undefined ) {

// Use the correct document accordingly with window argument (sandbox)
var document = window.document,
	navigator = window.navigator,
	location = window.location;
var jQuery = (function() {

// Define a local copy of jQuery
var jQuery = function( selector, context ) {
		// The jQuery object is actually just the init constructor 'enhanced'
		return new jQuery.fn.init( selector, context, rootjQuery );
	},

	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,

	// Map over the $ in case of overwrite
	_$ = window.$,

	// A central reference to the root jQuery(document)
	rootjQuery,

Open in new window

but on a separate jquery file, cookie.js shown below, the structure of the code is different ...
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

Open in new window

I want to make sure I am writing the newly inserted code in the correct place. Also, how is renaming each "$" to "jquery" in each file going to help. What is the difference? Isn't the end result going to conflict on the new name "jquery"? Wouldn't each external file need a separate name like "jquery1" and "jquery2" for file 1 and file 2?
0
 

Author Comment

by:vpit
Comment Utility
Ok, here are some baby steps ... I removed all of the external jquery files from the master page except one. I kept the jquery-1.7.2.js file and then wrote an jquery alert("Hello World"); on a UserControl. It now works! Once I removed all but one jquery file the alert was called. When I had multiple external jquery files the alert was NOT called thus indicating some sort of conflict. Now to move on to how to fix it so that I can successfully reference all my needed jquery files without having a conflict.
0
 

Author Comment

by:vpit
Comment Utility
Moving forward without messing around with the jquery.noConflict .... I removed sequential versions of some jQuery references and am only calling version 1.8.0.min.js now. I have validated that jQuery is loading through this script ...
<script type="text/javascript" language="javascript">
if (typeof jQuery == 'undefined') {
alert('jQuery has not been loaded!');
}
</script>

Open in new window

Why can I not utilize jQuery's autocomplete with my asp:GridView? I figure it is one of three possible things:
1. I have written my code incorrectly
2. I have omitted some code that is necessary
3. Or it cannot be done

I have a strong feeling it is either option 1 or option 2.
Please help!
0
 
LVL 15

Expert Comment

by:colly92002
Comment Utility
If you can run it in debug mode in Visual Studio then you can step thorough your jQuery script which may explain what is going wrong.

I do this by creating a solution file to deploy my jQuery scripts, and deploying that from Visual Studio, but there are other ways. See:
http://stackoverflow.com/questions/5753715/can-i-use-visual-studio-2010-to-debug-javascript-and-let-me-stop-and-watch-varia
for examples.
0
 

Author Comment

by:vpit
Comment Utility
I do not yet have a working solution to this problem. Any other ideas?
0
 

Author Comment

by:vpit
Comment Utility
Please close. I have not received a workable solution.
0
 

Accepted Solution

by:
vpit earned 0 total points
Comment Utility
I could not get this solution to work and gave up. I implemented a different AJAX solution completely.
0
 

Author Closing Comment

by:vpit
Comment Utility
There was no solution that worked.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

The vision: A MegaMenu for a SharePoint portal home page The mission: Make it easy to maintain. Allow rich content and sub headers as well as standard links. Factor in frequent changes without involving developers or a lengthy Dev/Test/Prod rel…
I thought I'd write this up for anyone who has a request to create an anonymous whistle-blower-type submission form created using SharePoint 2010 (this would probably work the same for 2013). It's not 100% fool-proof but it's as close as you can get…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now