Create a SharePoint Contextual Search Box in a Content Editor Web Part

SharePoint provides a couple of ways to search on a web part page. First, the Master Page can include a search box which can be set to search within a specific context such as the entire site collection, the current site, or (if on a list view page) the current list or library. The other way to add a search box is to use the Search Box web part. This can also be set to search within a specific context by adjusting the web part settings.

However, in some cases this may not be a good option. For example one of my recent projects required adding a contextual search box on the home page of a site that would search a specific list within that site. The stakeholders wanted to have more control over the layout, so the search box could not be in a separate web part; it had to be included within some other content on the page. Fortunately this turns out to be fairly easy to do with a little JavaScript.

SharePoint uses a URL query string to deliver search results. For example, to search for the word “test” within the “projects” list on the current site, the URL would look like this:

http://server/site/_layouts/OSSSearchResults.aspx?k=test&cs=This%20List&u=http://server/site/lists/projects

The URL starts with the search results page (OSSSearchResults.aspx for MOSS 2007 and Standard/Enterprise 2010 or SearchResults.aspx for WSS 2003 and Foundation 2010 – update your code accordingly), which is in the “_layouts” virtual directory. The “k” parameter includes the search terms. Next the “cs” parameter specifies the context of the search (“This Site” or “This List”). Finally the “u” parameter specifies the location of the context (the site or list URL).

We can use JavaScript in combination with a text input field and a button to generate a URL query string for searching. First, create the text input field and button:

<input id="searchBox" name="searchBox" type="text" />
<input id="searchButton" name="searchButton" type="button" value="Search" />

Next, create a JavaScript function that will build the query string and navigate to the resulting search page. We also need to create a function to check for when the user presses the Enter key because our text input is not in its own web form (you can’t use <form> tags on SharePoint pages because the entire page is already a form). We’ll use three parameters for the search function:

  • type – specifies if the context is a site or a list
  • site – specifies the location of the current site
  • scope – specifies the location of the site or list that you wish to search
<script type="text/javascript">
	// Search for the terms when the Search button is clicked

	function customSearch(type,site,scope) {

		var searchUrl = site + "/_layouts/OSSSearchResults.aspx?" // Or "/_layouts/SearchResults.aspx?" if WSS 2003 or SP2010 Foundation
		var searchTerm = "&k=" + document.getElementById("searchBox").value;
		var listParams = "&cs=This%20" + type + "&u=" + scope;
		document.location.href = searchUrl + searchTerm + listParams;

	}

	// Initiate the customSearch function when the Enter key is pressed

	function searchKeyPress(e) {
		// look for window.event in case event isn't passed in
		if (window.event) { e = window.event; }
		if (e.keyCode == 13)
		{
			document.getElementById('searchButton').click();
		}
	}
</script>

Finally, add the appropriate functions to the onclick and onkeypress events, including the values for the search function:

<input id="searchBox" onkeypress="searchKeyPress(event);" name="searchBox" type="text" />
<input id="searchButton"  name="searchButton" type="button" value="Search" onclick="customSearch(
 	'List',
	'http://server/site',
	'http://server/site/lists/projects'
);" />

Now put it all together:

<script type="text/javascript">
	// Search for the terms when the Search button is clicked

	function customSearch(type,site,scope) {

		var searchUrl = site + "/_layouts/OSSSearchResults.aspx?"
		var searchTerm = "&k=" + document.getElementById("searchBox").value;
		var listParams = "&cs=This%20" + type + "&u=" + scope;
		document.location.href = searchUrl + searchTerm + listParams;

	}

	// Initiate the customSearch function when the Enter key is pressed

	function searchKeyPress(e) {
		// look for window.event in case event isn't passed in
		if (window.event) { e = window.event; }
		if (e.keyCode == 13)
		{
			document.getElementById('searchButton').click();
		}
	}
</script>

<input id="searchBox" onkeypress="javascript:searchKeyPress(event);" name="searchBox" type="text" />
<input id="searchButton"  name="searchButton" type="button" value="Search" onclick="javascript:customSearch(
 	'List',
	'http://server/site',
	'http://server/site/lists/projects'
);" />

The script can be reused on multiple pages/sites for multiple contexts. The only thing you need to change are the values passed to the function in the onclick event.

<input id="searchBox" onkeypress="searchKeyPress(event);" name="searchBox" type="text" />
<input id="searchButton"  name="searchButton" type="button" value="Search" onclick="customSearch(
 	'[Site or List]',
	'[URL of current site]',
	'[URL of list or site to search]'
);" />

You can substitute your own values to customize the search for your site and/or list. Note that when providing the URLs for the site and scope parameters, don’t include a specific page or view; only include the root path to the site and/or list:

IncorrectCorrect
sitehttp://server/site/pages/default.aspxhttp://server/site
scopehttp://server/site/lists/projects/allitems.aspxhttp://server/site/lists/projects

Update: I’ve posted a newer version of this solution that allows for multiple search boxes on the same page. The code is similar, but I highly recommend using the updated solution for better flexibility. View it here:

About Josh McCarty

Josh McCarty is a web designer/developer and all-around technology enthusiast located near Phoenix, AZ. He specializes in developing innovative SharePoint solutions that go beyond the out-of-the-box capabilities of the platform using jQuery, XSLT, and other tools in the “middle tier.” Josh also develops custom websites and plugins for the WordPress platform with a focus on HTML5/CSS3 and responsive design. In all of his projects he emphasizes the user-experience, promotes modern web standards, and leverages the latest technologies available.

12 Responses to Create a SharePoint Contextual Search Box in a Content Editor Web Part

  1. Alex says:

    Thanks for this great post and simple solution, but I’m having an error when I try this: whenever I input text into the searchbox, and click the searchbutton, the SharePoint search returns an error message, and the input it searched for is always “undefined”. I’m assuming it’s not passing the text inputted into the searchbox, but I’m not sure how exactly.

    Any help would be much appreciated

  2. Josh says:

    Alex, I just re-used this code on another site and it worked without any problems. Try manually entering the search query string (replace this with valid values on your environment): http://server/site/_layouts/OSSSearchResults.aspx?k=test&cs=This%20List&u=http://server/site/lists/projects
    That should work. Then double-check your code and make sure your id and name attributes on the input element match with the JavaScript.

  3. Betty B says:

    great explanations along with your solution! “See ya” in the USPJA jQuery class! I checked this out because of Matt’s reference!

  4. Very nice post Josh! Very good explained! Cu in the USPJA jQuery class, too.

  5. Pingback: SharePoint Contextual Search – Updated | JoshMcCarty.com

  6. Looks like OSSSearchResults.aspx is probably not valid in Foundation, not sure if Search Server Express could resolve this, but I found that substituting searchresults.aspx worked for me.

    • Josh says:

      Thanks for the heads-up Michael! I confirmed this as well in SP2010 Foundation. I used this in a MOSS 2007 environment so I was unaware of the difference until I saw your comment. I’ll update the article accordingly.

  7. D says:

    Hi Josh,

    I’m having the same problem as Alex. I think it has something to do with the web part thinking it’s still in Edit mode, not sure. Just wondering if you’ve encountered this issue and if so, how did you resolve it?

    cheers
    danielle

    • D says:

      Sorry guys… I managed to get it working… not sure what I was doing wrong.

      Alex, I don’t know if this comes too late for you, I think I know why it wouldn’t work for you. You need to make sure that the input box has an ID. Then to get the value of the Input box, you need to reference the javascript by using document.getElementById(“searchBox”).value

      cheers
      danielle

  8. Andrew says:

    Great tutorial, worked a treat. One thing though, would it be possible to modify this tool to only search within a specific view?

    • Josh says:

      Hi Andrew,

      There isn’t a way using this solution by itself because SharePoint doesn’t provide any parameters to limit the search results to a specific view. However, you could create a search results page with a Data View Web Part that has the same filters that your view has. Then you’d want to add a query string parameter to the DVWP and use XSLT to only show rows where a column contains the keywords from the query string paramter. Then you’d need to modify the JavaScript to point to the new search results page you created instead of the standard SharePoint search results page. It would require some fancy XSLT, but I think it would be possible. The solution would be a bit limited because it’s a filter, not a true search. If you added any columns to the list you’d need to manually update your DVWP to account for the new column (if you wanted to include the new column in your search, that is). That’s well beyond the scope of this solution, though.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">