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

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: http://joshmccarty.com/2011/05/sharepoint-contextual-search-updated/.

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.

(more…)