changing the intialprompt searchbox webpart javascript/jquery
-
29-09-2020 - |
Question
I have a page_layout in which I plan to be used by many pages, this page layout has a searchbox webpart, at the moment it has a generic 'Search...'. However what I want is to change it so it says 'Search in whatever page you are on'. I am not having trouble with getting the name of the page that I am on but the changing the initialprompt to what I want. I have tried the obivious things like document.getElementById('NBSwebpartSiteSearch').InitialPrompt = 'test';
Solution
Interesting - the 2013 behavior uses a function in the blur event of the search box to populate or hide the term 'Search...' as appropriate -- I'm guessing to support old IE versions instead of using the placeholder property...
So! What you need is:
//use this instead of immediate or jQuery ready because we want to manipulate SP generated markup
_spBodyOnLoadFunctionNames.push("searchPromptSetup");
function searchPromptSetup() {
function spPromptHider(searchDOMElement) {
//make sure you have a valid object
if (searchDOMElement) {
//give it a placeholder if it doesn't already have one
if (!searchDOMElement.placeholder) searchDOMElement.placeholder = "Search in whatever page you are on";
/*use SP's javascript to hide the 'Search...' prompt, note the $ here is not the jQuery alias...
the OR assignment is my lazy way of allowing the function to be used in the blur event later... */
var control = $getClientControl(searchDOMElement) || $getClientControl(this);
control.hidePrompt();
}
}
var searchBox = document.getElementById('<yoursearchboxid>');
// if you don't add this listener to the blur event it will just reset to 'Search...'
searchBox.addEventListener("blur", spPromptHider);
spPromptHider(searchBox);
}
The above will only work with browsers that support the placeholder attribute... but you could expand upon it to add support for those that do not.