logo

Creating a simple search box

CodeStore is not alone in having a search input box on every page - Notes.net has one, as do most sites where the user wants to look for certain information straight away, rather than simply browsing from link to link. Some examples:

image

Adding the functionality is fairly easy, as I shall describe below. What is not so obvious is how to get around the problems associated with the way in which the browser handles submission of this form. This is what a couple of people have asked me about and hence why I am writing this article.

Creating the Search Box:

Because we want to add the same box to every page and probably have it in the same place, it is best to create the box in a Subform. This way you can easily add it to every form and when you make changes they get updated to all necessary pages. This is what the box we are going to create will look like:

Search


This is simply a table with two rows and two columns. The first row is merged in to one column and the second row contains the search box and the search button in respective cells. To create this table we could easily use the Notes Table element in the designer, but I prefer to use Pass-Thru HTML as this gives me greater control over what is sent to the browser. Here is what my Subform looks like so far:

image

Notice that even the search field has been created in HTML. Why? Well, because the subform is not only going to be on forms, but also on documents in read-mode and views. When on a document in read mode a standard Notes field will not be seen as a field. The method we use makes use of the fact that Domino still renders a <form>, even in read-mode, so we can have fields on there.

What we do need to do though is add a Notes field to the form with the same name as the search box (Domino errors if you don't). We shall add this field to the subform, this way we are sure it is on every form with the search box. The field is Computed For Display (so that it's not stored in the document) with a value equal to itself and it is hidden. The subform will now look like this:

image

Notice the pink lines of text on the subform. You can do away with these if you like. Personally, I find them a useful way of highlighting that it is a subform and it also shows me where it starts and ends, when it is on the form.

We now have a subform that we can place on all our forms and it will add a tidy little search box. The only thing we need to do now is make it work...

Adding the search functionality:

Regular users of this site will know by now about my love affair with JavaScript. That's what we are going to use. First thing to do is add a call in the onclick event of the "GO!!" button to the function we are going to write. The HTML for the button should look like:

<input type="button" name="Search" value="GO!!" onclick="doSearch(this.form.Query);"/>

Now, when the button is pressed, it calls the doSearch function and passes the Query field's object to it. All we need now is the function to do the search. How one writes this function depends on how flash one wants to make it. I am going to show two versions; a simple one and a flashy one. Let's start with the simple one:

function doSearch ( s ) {
openDbRelativeURL("All?SearchView&Query=" + s.value);
}


This is all we need. All it does is redirect the browser to a new URL that points to a view and opens it using the ?SearchView URL Command, passing it the search term via the Query parameter. To make it even simpler we could have put this one line of code in the onclick event of the button and done away with the function.

You have probably noticed the strange looking call to a function called openDBRelativeURL(). Don't worry, it's not some magical JavaScript feature you never knew about. It's something I wrote so there is no need to work out the Database's filename when creating the URL. You will need to add this to your set of JS functions as well. You can read more about it here or just copy it from below:

function openDbRelativeURL( url, target ){
//Check we have a target window;
target = (target == null ) ? window : target;
//Work out the path of the database;
path = location.pathname.split('.nsf')[0] + '.nsf/';
target.location.href = path + url;
}

So, what's wrong with this simple version of the doSearch function? Nothing, as such, we just need to make it a little more user friendly. The flashy version below does two things. Firstly, it makes sure that the user has entered something to search for, thus preventing an error from the server. Secondly, it uses Regular Expressions to validate what they are searching for. This checks for things like the word "field" and characters such as [ and ), all of which are more than likely going to return an error.

function doSearch ( s ) {
var regExp1 = /\bfield\b/;
var regExp2 = /[(,),<,>,\[,\]]/;
var str = s.value; if ( str == "" ){
alert("Please be sure to enter something to search for.");
s.focus();
} else {
if ( typeof regExp1.source != 'undefined' ) //supports regular expression testing
if ( regExp1.test( str ) || regExp2.test( str ) ){
var alrt = "Please note that you can not include:";
alrt += "\n\nThe reserved word 'field'\nthe characters [, ], (, ), < or >";
alrt += "\n\nin your search query!\n\nIf you are confident that you know";
alrt += "\nwhat you are doing, then you can\nmanually produce the URL required."
s.focus();
return alert( alrt );
}
openDbRelativeURL("All?SearchView&Query=" + escape( str ) + "&start=1&count=10");
}
}


It's at this point that I would normally include a working example. Obviously I don't need to as there is already one on every page ;) If you want to include one on yours then just plug in all the components from above.

A couple of gotchas

If you were to add the above parts together and play around for a while you would, sooner or later, notice a little "bug" in this method. The problem is that when you have a form with only one field in it and you press the enter key the browser thinks you want to submit the form. Because the action of the form will be to submit it, rather than do a search, you will get some confused users. What we need to do is alter the onsubmit property of the form when we know there will only be one field. We only need to do this in documents in read mode and in things like $$ViewTemplates.

If you are lucky enough to be using R5 this is fairly simple. In the onsubmit event of the form, add the following line:

image

This tells the browser that when the form tries to submit and the document is in read mode it should simply call a function called return false instead. Before we look at this function we need to add the isDocBeingEdited variable to the page. Easiest way to do this is add the following line to the HTML Head Contents ($$HTMLHead) of the form:

"<script>var isDocBeingEdited = " + @If(@IsDocBeingEdited; "true"; "false") + ";</script>"

Note: On things like $$ViewTemplates, which can never be in edit mode, you don't need to add this variable and the onsubmit event is simply: return returnFalse(this.Query);

All we need now is the returnFalse function. The way you write this depends on what you want to happen when the user presses enter. The three option being: do nothing, do the search or tell the user to press the button.

function returnFalse(s){
//guess the field if not supplied
s = (s == null) ? document.forms[0].Query : s;

//if you want to do the search, use this line
//doSearch(s);

//if you want to alert the user, use this line
//alert('Please use the \'Go!!\' button to do a search');

//this line should always be here!!
return false;
}


And there you have it. It might seem overly complicated but this approach covers just about everything you are likely to come across when designing a search box for your site.



Note: If you are using R4 you will not be able to set the onSubmit event of the form in the Domino Designer IDE. You will have to do it with JavaScript.

If you are using IE then the following script will do it:

<script for=window event="onload()">
document.forms[0].onsubmit = returnFalse;
</script>

If you are using NN then you will need to add the following JS near the bottom of the form somewhere:

<script>
document.forms[0].onsubmit = returnFalse;
</script>

Obviously you will need to hide both scripts when the forms are being used in edit mode.

Feedback

  1. Creating a simple search box

    Thanks Jake. I've been looking for something like your simple search form. It's simple, yet brilliant. Your tips and site are both excellent! From a happy and appreciative regular visitor.

    1. Re: Creating a simple search box

      Don't mention it Jon. Glad you liked it. I had a feeling when I wrote this one that people would like it. It is often some of the "simple" things that can leave us all thinking how...

      If anyone else has any simple things that they need explaining. Let me know...

      Jake -CodeStore

      Show the rest of this thread

    2. Creating a simple search box

      plz tell me how can i add a search box in my website which will search the page of my website only

      I need it badly.

  2. What if I WANT to submit with enter?

    Jake, Love your site! Wonderful job and the articles are simply brilliant.

    I have been struggling with a searchbox similar to yours today (unknowingly of your example which just proves it again: before you start - check out Jakes site to avoid reinventing the wheel...). But I actually want to ALLOW my users to submit the query with Enter which I feel is more userfriendly. But it's close to impossible, or maybe I'm overlooking something basic!

    I try to catch the onSubmit event and instead of return false, I call my searchfunction in Javascript. But, the URL in my browsers addressfields wont change to the computed Javascript string. It just takes whatever is in the location.href and adds my querystring !! If I put the exact same function on a button it works. Argh!

    I tried several different ways to get around this but the result is always the same. If you (or someone else) have a working example of this in action, I would be more than happy.

    1. Re: What if I WANT to submit with enter?

      First of all thanks to all of you for the kind words. This is the fuel that keeps me working on the site.

      Don't worry about listing this site in any code as, at the end of day, who knows!?

      Anyway on to the problem. As Jonathon said, yes you can.

      In the article in the function called "returnFalse". In here there is a line of code commented out that looks like thuis: [<br clear="all" /><code class="JavaScript">] //doSearch(s); [</code>] If you remove the "//" then this will mean the search is performed when the user hits enter....

      Jake -CodeStore

      Show the rest of this thread

  3. Using an image instead of a button

    Is it possible to replace the "type='button'" with "type='imag'"?

    1. Re: Using an image instead of a button

      erm in theory (and that a big one) this should work:

      <a href="javascipt:doSearch(this.form.Query);">

      insert your notes button here

      </a>

      Show the rest of this thread

    2. Re: Using an image instead of a button

      I was able to use an image for a submit button using the following code: (The trick seemed to be the return false; statement. Otherwise it would return x & y coordinates and not call the doSearch function)

      //<input type="text" id="oName" accesskey="S" name="Query" size="20" maxlength="40" title="Enter your query in here !"/> &nbsp<input type="image"onClick="doSearch( this.form.Query ); return false;" src="/pathtoimage/go.jpg?OpenImageResource" border =0>

    3. Re: Using an image instead of a button

      Instead of using the <input> tag of type="button" like: <input type="button" name="Search" value="GO!!" onclick="doSearch(this.form.Query);"/>

      Have you tried using the <button> tag? I'm not sure if the <button> tag is available with Netscape. I have only used in it in IE 5+.

      Here's an example. <button name="Search" onclick="doSearch(this.form.Query);"><img src="/icons/schview.gif"> Go!</button>

      if my pass-thru html works it will look like this: [<button name="Search" onclick="doSearch(this.form.Query);"><img src="/icons/schview.gif"> Go!</button>]

      A Print button could use: <button onClick="window.print();"><img src="/icons/actn147.gif"> Print Me!</button>

      again, if I have the right pass-thru html it will look like this: [<button onClick="window.print();"><img src="/icons/actn147.gif"> Print Me!</button>]

  4. You Rock Jake (how to handle the return keystroke)

    I wrote an app a while ago that had a search field on various web pages, but I never knew how to get around whe a user just hit return.

    using your tip, I just added "return goSearch();" to the onSubmit and it almost worked right away.

    I did have to add the "return false;" to the end of my goSearch() function otherwise, I got an error. I'm not the best at Javascript, so I'm not sure what the deal was, but it works all the time now.

    1. Great subject a few hints for beginners

      Really enjoyed the article. Had a few hints for those who have not done much previously with view templates.

      On the form page can 1) Also add the Alias $$SearchTemplate for All (if you wish to use "All" view) else it will use the default template 2) to put a field $$Viewbody in the form,

      Plus in the subform on line 3) openDbRelativeURL("All?SearchView&Query=" + escape( str ) + "&start=1&count=20"); "All" this is the name of the view the documents are being pulled from

      Can select any view as long as make changes to the steps 1, and 3.

      Show the rest of this thread

  5. Great tip, one small change...

    I love the way you check for invalid characters and the "field" keyword in your code. There is one minor thing to correct if you don't want the user to use the field keyword at all: at the moment you perform a case sensitive test for "field", so the user could enter "Field" or "FIELD" (Domino doesn't care). To make your test case sensitive just change the line declaring the first regular expression: var regExp1 = /\bfield\b/i (added the i at the end for ignore case). That's it.

    Thank's again for the great tip!!!

  6. $$ViewTemplates

    Hi Jake,

    My site uses framesets, with $$ViewTemplates usedto format the views. When I created the subform and included it in one of the view templates, I found that the Javascript functions were being passed a paramater of "undefined" until I removed the Notes Field from my subform.

    The search actually ran, however it was continually searching for the text "undefined" (pretty obvious that there was an error happening in there somewhere!) and finding the document in my database that contained that text.

    Not entirely sure how what I'm doing is drastically different to anyone else here, but it just drove me crazy for a few minutes while working that out, so I thought I'd post in case anyone else has their site setup in a similar fashion.

    Ross.

    1. Re: $$ViewTemplates

      I had similar problems. Turns out that when you tell Notes to "Generate HTML for all fields", you get an extra (hidden) input field for the Computed-for-Display field, with the same name as the Search field. And of course, this is empty, which causes the "undefined" result. For now, I have hidden the search box (in my case, a subform) when I _have_ to use the "Generate HTML for all fields" option, and the Form is in edit mode.

      • avatar
      • Robert Garand
      • Fri 28 Jun 2002

      Re: $$ViewTemplates - Solution

      When using a $$ViewTemplate, DO NOT place a Notes 'Query' field on the form (or subform if that is what you prefer to use).

      When performing the query, the query uses the Notes 'Query' field and not the HTML field you coded. Therefore the Query is "" and undefined.

      Other than that the code works great. (Thanks Jake!!)

      If you use '$$ViewTemplate for Viewname' you can replace 'All' with 'Viewname' if you only want to search the view that is currently displayed. (Unless you place the 'function doSearch' somewhere other than the subform (if that's what you use), you can't control which view is used for the query.)

      Change --> openDbRelativeURL("All?SearchView&Query=" + s.value);

      To --> openDbRelativeURL("{ViewName}?SearchView&Query=" + s.value);

      One problem I have run into: I have not found a way to capture the name of the view that $$ViewTemplateDefault is displaying when using an embedded view or $$ViewBody field. If I were able to capture that and assign a variable or populate a field, I could use that variable in the openDbRelativeURL command to only search the displayed view.

      If you've got an answer to capturing the view that $$ViewTemplateDefault is displaying, it would be appreciated.

      Show the rest of this thread

    • avatar
    • gary
    • Fri 11 Jan 2002

    Partial Search

    Is there a parameter I have to change to do a partial search.

    If I search on television in my database I get 5 records returned.

    If I search on tele nothing is returned.

    Thanks.

      • avatar
      • Ben
      • Fri 11 Jan 2002

      Re: Partial Search

      The option you're looking for is "use word variants".

      I can't remember how it works on the web (it's been a while) but you can always look in the search site database to see how it works.

      ;0)

      Show the rest of this thread

    1. Re: Partial Search

      To enter a partial word you need to append the * wildcard to the end of your query.

      Jake -codestore

    • avatar
    • sony
    • Thu 17 Jan 2002

    Why I got the login promt?

    I used the "simple search box" in my database. when I preview the form(search) and write a word on seach box and push the "Go", så I got the Login promt. I check the ACL and property on the Form & Views, everything is OK. Do you know why its happen?

    thanks

      • avatar
      • Ben
      • Thu 17 Jan 2002

      Re: Why I got the login promt?

      This happens when the form you have your box in is not marked public.

      Doing a search is in fact creating a document, therefore the form you are using needs to be marked as public.

      To do so, create a computed field named $Public and put "1" as the value.

      That should work.

      Show the rest of this thread

    • avatar
    • dan
    • Sat 2 Mar 2002

    Trapping Enter key

    Great site. Had trouble with the code to trap the enter key on a View Template.

    Found this instead on Notes.net which seems to work as passthrough html. It also avoids having to go into the form properties, so it can be in the subform.

    --Dan

    </script> <SCRIPT Language="JavaScript">document.forms[0].onsubmit=new Function("alert('Enter Key Disabled. Choose a Link or Button');return false;");</SCRIPT>

  7. Using FIELD in the search

    Jake

    I have checked this out and my one comment would be regarding the exclusion of the reserved word FIELD.

    I use two types of search within one of my sites - one is a wildcard, which uses the searchbox as you described. The other uses SELECT or dropdown boxes for country, company and initial. I use the same doSearch code (because it executes MUCH quicker than an agent using FTSearch) which does something like this:

    if(country =='<-Select Country ->' ) { searchstring=''; } else { searchstring='FIELD Country=' + country; }

    if(company =='<- Select Company ->' ) { searchstring=searchstring + ''; } else { if (searchstring == '') { searchstring='FIELD CompanyName=' + company; } else { searchstring=searchstring + ' AND FIELD CompanyName=' + company; } }

    if(initial =='<- Select First Initial of Lastname ->' ) { searchstring=searchstring + ''; } else { if (searchstring == '') { searchstring='FIELD LastName =' + initial + '*'; } else { searchstring=searchstring + ' AND FIELD LastName =' + initial + '*'; } }

    if (searchstring==''){ alert("You must select at least one item"); return false; }

    window.status='Searching...'; doSearch(searchstring,'1');

    The additional parameter just forces the doSearch to ignore the reserved words check.

    tq

    • avatar
    • Jeniffer
    • Wed 10 Apr 2002

    SearchBox

    I did the searchbox function to work in my website. Do you know, how I can put the action "NextPage" or "PreviousPage" in the resultform. Thank you.

    1. Re: SearchBox

      Here is the code for my previous and next links:

      Previous

      ThisDBW := @ReplaceSubstring (@Subset (@DbName; -1); "\\" : " "; "/" : "+"); @If((@Text(Start)>"1"); "{<a class=ul href=\"/" + ThisDBW + "/Search?SearchView&Query=" + @ReplaceSubstring(Query; " "; "+") + "&Start=" + @Text(Start - Count) + "&Count=" + @Text(Count) + "&SearchWV=1&SearchFuzzy=1\">&lt&ltprevious</a>}"; "&lt&ltprevious")

      Next

      ThisDBW := @ReplaceSubstring (@Subset (@DbName; -1); "\\" : " "; "/" : "+"); @If((Hits >= Count); "{<a class=ul href=\"/" + ThisDBW + "/Search?SearchView&Query=" + @ReplaceSubstring(Query; " "; "+") + "&Start=" + @Text(Start + Count) + "&Count=" + @Text(Count) + "&SearchWV=1&SearchFuzzy=1\">next&gt&gt</a>}"; "next&gt&gt")

      Ed's Note: Replace {} brackets with [] brackets.

  8. ACL for searchbox to work...

    Thanks for the article - great help.

    In case this helps anyone else: I tried it successfully with a whole string of dbs and then got stuck on one where the 'Query' field was apparently passing 'undefined' to the URL. I was stumped. It was only after TWO HOURS of hair pulling that I figured out that the error was due to ANONYMOUS users only having 'Author' access without the option to create documents checked! [Make sure you use a SaveOptions field]

    The other thing that I can't figure out is how to get the submission using Enter to work without causing an error in Notes when documents are created: I'm working in R5 and tried using the HTML you suggested for R4 in without success - it would be great to have an onSubmit event for the subform so that it can be hidden completely from the Notes client...

    Thanks again...

    1. Re: ACL for searchbox to work...

      I tried capturing key presses and stuff but in the end the simplest solution (for me..) was to capture and redirect the submission process: this idea came from some other part of Jakes site.

      var query = document.forms[0].BodySearchString.value ; if (query == "enter search here" | query == "") { return false; } else { buildurl( query ); return false; }

      in the onSubmit event for the form and (simplified)

      function buildurl (query){

      if (query == "enter search here" | query == "") { alert( "please enter text to search"); return false; } else { //default alternative top.location.href ="./SearchFrameset?OpenForm&SearchString=" + query; //url opens new frameset with search string embedded in the search field in system navigator } }

      On the page/form there is a button

      <INPUT NAME=Search TYPE=button VALUE="Go" style="color='#000000';" onClick="buildurl(document.forms[0].BodySearchString.value);"/>

      Note the return false statements in the querybuilder function and onSubmit event - they are the equivalent of exit sub in script.

      feel free to contact me if you have any questions.

    2. Re: ACL for searchbox to work...

      What kind of errors are you getting in the Notes client? I hope I am understanding your question correctly.

      If you're working in R5, you can modify Jake's call to the doSearch function by checking for the JavaScript property appName.

      An example:

      if (navigator.appName != "Lotus Notes") { doSearch(s); }

      This way, the JavaScript that follows will not execute in the Notes client.

      If you're looking for a workaround in an R4 environment, you can essentially hide a subform from the client by checking for $$Web in @UserRoles.

      So your subform formula would look something like:

      @If(@IsNotMember("$$Web"; @UserRoles); "NotesClientSubform"; "BrowserSubform")

      I hope this helps.

      Bill

    • avatar
    • tabbat
    • Thu 2 May 2002

    The color of result search

    very simple and easy way too search. I would like to chaneg the color of search result word (its green). How can I do it? thanks

      • avatar
      • D Grimes
      • Fri 3 May 2002

      Re: The color of result search

      try "&Highlight=0,<word to highlight>" in the URL string.

    1. Re: The color of result search

      You can't change the "&Highlight" colour used, if that's what you mean...

      "&Highlight" is an undocumented "feature" in R5, as Iris don't yet know exactly where they're going with the functionality. Try and search for it in the Domino Designer help file, and you'll see what I mean.

      In other words, it's like unexposed Notes API calls -- use at your own peril -- and doesn't work consistently in R5.

      Check out the LDD on this also, specifically this thread:

      http://www-10.lotus.com/ldd/46dom.nsf/55c38d716d632d9b8525689b005ba1c0/e658ac78f 692cdc085256893005029bc?OpenDocument

  9. Adding a Graphic Go Button

    This tech note was such a help, I just had to give something back.

    To get a graphic button to work, create a computed for display field. We'll name it SearchButn. In the formula put:

    "{<a href=\"Javascript:doSearch(document.forms[0].Query)\"> <img border =0 alt =\"Click to launch the SEARCH\" src ="+DbReferer+"/go_Army.gif></a>}"

    Then on your form, (in my case $$ViewTemplateDefault), create another hidden field called DbReferer, I made mine editable, with the formula:

    @Text("/" + @ReplaceSubstring(@Subset(@DbName;-1);"\\" : " "; "/" : "+"))

    One thing to note, to get it to work, I had to change the doSearch call from "this.form.Query" to "document.forms[0].Query" as shown above or it kept giving the error about not having the object this.form.Query.

    Jake - Thanks for super site! Bill

    [<strong>Editor's Note:</strong>] Replace the {}s in the above code with []s.

    1. Re: Adding a Graphic Go Button

      Cheers Bill,

      Thanks for clearing this up for people. Almost an FAQ by now... ;o)

      The call to "this.form" doesn't work for the image as it isn't an element on the form whereas the button was. Hope this makes sense...

      Jake -codestore

    • avatar
    • jerome vaure
    • Thu 1 Aug 2002

    how to deal with foreign languages ?

    I'll use this comment as a "code store". I know this post won't make sense to everyone, so if you think that it's useless, feel free to delete it Jake !

    Sometimes you have to deal with users that don't use english nor boolean logic often. (i do)

    So we may need to : - change their native language "AND" and "OR" into the english one (that domino understands) - automatically add "AND" (or "OR") between the words (if not it seems that domino will look for the whole sentence) - deal with the special characters that can be wrongly indexed

    so here are a few javascript functions :

    // translate the french boolean operators into english var pattern = new RegExp(/\bou\b/gi); str = str.replace(pattern,"OR"); pattern = new RegExp(/\bet\b/gi); str = str.replace(pattern,"AND");

    // automatically add "AND" between words (if there is no operator in the query) if ( (!str.match(/\bor\b/ig)) && (!str.match(/\band\b/ig)) ) { pattern=/\s+/ig; str = str.replace(pattern, " AND "); }

    //remove the accents, diaeresis... pattern = new RegExp("[éëèê]", "gi"); str = str.replace(pattern,"e"); pattern = new RegExp("[ïî]", "gi"); str = str.replace(pattern,"i"); pattern = new RegExp("[àäâ]", "gi"); str = str.replace(pattern,"a"); pattern = new RegExp("[üûù]", "gi"); str = str.replace(pattern,"u"); pattern = new RegExp("[öô]", "gi"); str = str.replace(pattern,"o");

    all of this can be added in the doSearch() function.

    hope this helps...

  10. See result documents in a view

    Hi! This is a good method for send a search, but i need see the result documents in a view from a Browser.... anybody know how can i do it??

    Thanks in advance!

  11. Searching within a date range

    Hello Jake. I was just wondering how I can delimit results by searching documents within a window of two dates. Suppose I want to see documents created between two dates. Do you know how?

      • avatar
      • Jake Howlett
      • Fri 13 Dec 2002

      Re: Searching within a date range

      Like this:

      [<a href="srch?SearchView&query=[BlogDate]%3E=12/01/2002%20AND%20[BlogDate]%3C=12/11 /2002"> [BlogDate]>=01/12/2002 AND [BlogDate]<=11/12/2002</a>]

      IMPORTANT BlogDate is (and needs to be!) a [<b>Date</b>] field on my Blog form!

      Jake

    • avatar
    • Larry Lizzard
    • Mon 6 Jan 2003

    Standing on the shoulders of giant Jake

    In Holland we have a saying: standing on the shoulders of giants, even a midget can look further ahead. Standing on the shoulders of giant Jake, I can combine two of his ideas: - a pure html form on any page - the ?CreateDocument url string (see the url cheat sheet on notes.net)

    in any form/page/view/etc: put the following pass-through html:

    {/form}{form action="Return?CreateDocument" method="post" enctype="multipart/form-data"}{input name="searchQuery" type="text" SIZE=45 MAXLENGTH=90 value=""}{input type="button" value="Search" onclick="if ( this.form.searchQuery.value==''){return false;} else {this.form.submit()}" /}

    replace { and } by < and >.

    The above creates a form on your form/page/view/etc with a field called searchQuery and a submit button next to it.

    Create a form "available to Public Access users" called "Return" with two fields: searchQuery (editable, text) and $$Return (computed, text). Make all the required calculations on the searchQuery field in the $$Return field.

    e.g. "[/yourdatabase/yoursearchview?SearchView&Query=" + searchQuery + "&SearchWV=FALSE]"

    (keep square brackets)

    That is it, simple and effective.

    Additional advantages: 1) It gives you the ability to create Google style search queries as described in:

    http://www.codestore.net/A55692/store.nsf/all/339186C51DA90D7E86256B5E007A7991?O penDocument

    2) It also gives you the opportunity to create view with all the saved "Return" forms to see what people are searching for.

    3) Also, the pass-through-html form submits on enter when the cursor is in seachQuery field.

    4) It easily combines with other html forms on the same page.

    Thank you Jake for your more than superb site. Visit it daily, couldn't sleep for two weeks while you were on holiday.

      • avatar
      • Larry Lizzard
      • Mon 6 Jan 2003

      Re: Standing on the shoulders of giant Jake

      p.s.

      5) works also in Notes 4

      6) only 1 line of javascript needed, but can be combined with Jakes fieldcheck script for not allowed search querys like the word "field"

      7) even works when a document is in edit mode. If you don't want the search box on a document that is in edit mode, you can hide the pass-through-html selecting the checkbox "Hide when opened for Editing".

      What is REALLY nice if you put on the $$SearchTemplateDefault form a hidden editable text field called "Query_String_Decoded" and the not-hidden editable text field called queryString which has the default value of "@Trim(@ReplaceSubstring((@Middle(Query_String_Decoded;"&Query="; "&"))". Users can thus see what they have searched for and when you add a new search button next to it, they can alter their search query easily and resubmit it with one click.

  12. s has no properties.

    When I tried to use your code to create a search box, I got the abovementioned error.

  13. Why not create a new form for the search box?

    Hi,

    I was wondering.

    If you place the query field and submit button in a seperate form you don't have to create an addictional Query field in your subform. You can directly adress your form field value by 'document.searchform.value'.

    this is the way i would do it :

    </form> <form name="searchform" action="something" methos="post"> <input type="text" name="query"/><br/> <a href="JavaScript:search(document.searchform.value);">Search</a><br/> </form>

    Make sure not to break up your Notes form. This can be avoided by making a seperate edit (client) and view (HTML and computed fields) section in your forms. I personaly like the 'form' way better. This way you divide the Notes form from the search part.

    Or am I missing something and am I bound for errors?

    p.s. Great site. I practicly learned to develop notes apps through your site :). Thanks for sharing.

    1. Re: Why not create a new form for the search box?

      Jake - Totally excellent. I've already used this on two different web sites, and my company loves me (no raise though)

      But, I've run into a problem. I have a custom search results page and use @URLOpen to move from page to page. They want the search box on this one too. However, when I hit the Next Page, the OnSubmit gets called, and it tests for text in the box. How do I check to see if it's a URLOpen or a return or a hit on the "Go Search" graphic?

      Show the rest of this thread

  14. JavaScript novice pulling my hair out.

    Jake,

    I'm at wit's end. I had great difficulty finding documentation to creat a simple search box using Domino Designer R5. I was thankful to find your page on codestore.net.

    I followed your directions very carefully, making only slight changes to the Pass-Thru HTML.

    Here is the URL link to my resulting test form containing the "SearchBox" subform:

    The full-text index for the database is up to date. But when I run a test by typing in words such as "pins" "S-2000" "bushings" or "dowels" I get a Microsoft JScript runtime error box with "Line: 51" and "Error: Object expected" explanations.

    What step am I missing? I really need to get this function up and running soon. Thanks.

    1. Re: JavaScript novice pulling my hair out.

      Looking at your source code I can see you are missing the function called openDBRelativeURL() in your JavaScript code. The function should be in the article somewhere...

      Jake

      Show the rest of this thread

      • avatar
      • Greg
      • Wed 20 Aug 2003

      Re: JavaScript novice pulling my hair out.

      I too am a javascript novice and I'm hitting one snag here. Using Jake's first example, the non-sexy search - my search results keep loading in the frame where my Search button is. I have a main central frame entitled "NotesView" which is where I want to see my Search Results. Where in the function(s) do you specify the target frame and how? Thanks!

      Show the rest of this thread

  15. Searching Attachments

    Thank you for the great big helping hand. I am new to JavaScript and was in desperate need of this.

    I have it working, with one problem. I use 3 forms for my site - one for main page content, one for creating objects from Word documents, and the third to attach PDF files. My database is full-text indexed and up to date. When I use the regular Notes client search, it sees all of my documents created with all forms. When I use this web search, all I seem to be getting are the documents created from the main form so I am not getting my Word or PDF content.

    This database is a public website only accessed from the browser, but I do creation and testing from the Notes client.

    Does anyone have a clue what I can do to fix this?

    Thanks.

    • avatar
    • lisvard
    • Mon 29 Dec 2003

    Error

    I've following the instructions and am getting the following error "Run Time error has occurred..."

    Debug is targeting this line: <input type="button" class="button" name="Search" value="GO!!" onclick="doSearch(this.form.Query);" />

    Any ideas?

  16. help with my search box

    I've created a searchbox on my website but it does not work, and I have no clues as to what I need to do to corret the problem. I read your article but I did not know where I needed to put my information. I would like a search bar like mysimon.com. By the way I do not know much about html or Javascript. I'm using Frontpage 2003 and I'm learning as I go. My website address is www.lamericas.com. I've only published the homepage.

    Thank You

  17. Search Box Question

    I'm new with using Notes and I don't understand the hidden Query field.

    "The field is Computed For Display (so that it's not stored in the document) with a value equal to itself and it is hidden."

    I know how to make a Computed For Display field and hide it but how do I make it "with a value equal to itself"?

    Thanks. Any help is appreciated.

      • avatar
      • Jake
      • Wed 23 Jun 2004

      Re: Search Box Question

      Sorry about the confusion there. I can see why it might not be obvious...

      What this means is that you should simply type the name of the field itself in to the field's "default value" setting.

      Does that make more sense?

      Jake

      Hide the rest of this thread

      1. Re: Search Box Question

        Thanks Jake. I put "Query" in the value in the Formula panel. But for the

        <input type="button" name="Search" value="GO!!" onclick="doSearch(this.form.Query);"/>

        javascript, how do I put this in the onClick event of the GO button since this is written in HTML code and the button doesn't actually exist on the screen? I tried pasting this in the onClick event for the Form but I get an error message.

        Like I said I'm very new to this and any help is greatly appreciated. Thanks!

          • avatar
          • Jake
          • Wed 23 Jun 2004

          Re: Search Box Question

          The bit you need in the onclick event is:

          doSearch(this.form.Query);

          You also need to paste the doSearch() function in to the JS Header area.

          Jake

          1. Re: Search Box Question

            Thanks Jake.

            I'm a novice to JavaScript as well. I pasted the second function directly under the DoSearch() function in the JSHeader. Is that right?

            Also, I added the $$HTMLHead shared field at the top of the form which also has code from other forms in the database. I scrolled to the bottom of the code and added

            "<script>var isDocBeingEdited = " + @If(@IsDocBeingEdited; "true"; "false") + ";</script>"

            and get an error message: "An operator or semicolon was expected but was not encountered."

            Also, is $$ViewTemplates a view that I have to create?

            Basically, I have a frameset with a bunch of linked Forms in the main frame and want to create a search to search for text within those Forms. Does this make sense? Am I going about this the right way? Thanks Jake!

            1. Re: Search Box Question

              I followed all the directions on the site and when I click Go or hit Enter, I get "Form Processed".

              Do I need to enter a $$Return field somewhere or a $$ViewTemplates field?

              Thanks.

              1. Re: Search Box Question

                Here are the steps I followed to successfully implement this search box.

                1. On database properties --> First tab select from Web Access section and enable "Use Java Script when generating pages"

                2. Also on database properties --> 2nd from last tab --> create index

                3. Go into designer and create your subform (i.e. Shared code --> Subforms)

                4. once in your new subform a. Create a field name (Query) ** keep in mind of the case (javascript is case sensitive) b. Copy this code into your subform and make all text pass-thru html. Do not include the ** lines in your sub form.

                ** beginning of code <style type="text/css"> <!-- .style5 { font-family: Arial, Helvetica, sans-serif; font-size: 16px; color: #330066; font-weight: bold; } --> </style>

                <table width="409" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="62"><span class="style5">Search</span></td> <td width="269"> <input type="text" name="Query" size="40" /> </td> <td width="78" colspan="3"> &nbsp <input type="button" name="Search" value="GO!!" onclick="doSearch(this.form.Query);"/> </td> </tr> </table>

                ** end of code

                5. go to JS Header of subform and copy this code.

                function doSearch ( s ) { openDbRelativeURL("All?SearchView&Query=" + s.value); }

                function openDbRelativeURL( url, target ){ //Check we have a target window; target = (target == null ) ? window : target; //Work out the path of the database; path = location.pathname.split('.nsf')[0] + '.nsf/'; target.location.href = path + url; } 6. make sure you change the word "All" to the name of your view.

                7. Save the subform 8. Add subform to your form

                And that is all I did to make it work. I hope this will help in implementing this search.

                Thank you Codestore for step by step lesson.

                Ted Ford

    • avatar
    • marcus
    • Thu 1 Jul 2004

    thanks again.

    your site is helpful as always. i used this tip almost verbatim in an application last week. just wanted to say thanks, Jake.

    • avatar
    • Mat
    • Wed 25 Aug 2004

    In a frameset ?

    Hi

    Thanks for the code

    I'm a french guy (perhaps you couldn't undertsand me .. lol) and i want to use this code...

    but my web app has got frameset and i want to obtain the result of the search in another frame

    how could i simply parameter that ?

    thanks

      • avatar
      • Mat
      • Thu 26 Aug 2004

      Re: In a frameset ?

      Yep ! i've just found a solution... i chang function do Search into :

      function doSearch ( s ) { openDbRelativeURL("All?SearchView&Query=" + s.value,parent.frames["MyFrame"]);}

      hasta luego !!!

    • avatar
    • Marcio
    • Wed 10 Aug 2005

    Search Empty Field

    How I search empty field...i.e.

    fieldname contains(""), when I try this, a error ir returned

    Thanks

  18. I can't see the html in those screenshots!

    How do I copy the contents of the subform. I can't see it?

    • avatar
    • Dave C
    • Thu 17 Nov 2005

    Display Results in View

    Hi,

    First of all - very useful! (Even after 4 years!)

    Secondly - I have my search field in a $$ViewTemplate and can search the view fine, but can't seem to get the results to be returned in the same view. After the search, I want only the documents that match the search to appear in the same view. How do I do this? What am I doing wrong?

    Cheers

    DC

      • avatar
      • Jake Howlett
      • Thu 17 Nov 2005

      Re: Display Results in View

      "can't seem to get the results to be returned in the same view"

      I don't understand what you mean by this.

      Jake

      Show the rest of this thread

    • avatar
    • Dan
    • Tue 18 Jul 2006

    Simple search box on a page

    Is there a solution for using pages rather than forms / subforms? Our main page is a 'Domino Page' and we need the search box there as well.

  19. Creating a simple search box without Database

    Hi,

    I just red your tips regarding simple search box and you give me so much help while doing my page. Actually, the page that I'm currently doing now has no database but needs a search box so that my visitors can easily find the words/page/sections they need.

    I would like to ask if your script needs database? if so, can you help me to resolve my problem?

    It would be highly appreciated if you will assist me on this.

    Thanks!

    Grace

    • avatar
    • Tri
    • Mon 5 Apr 2010

    Absolutely fantastic. Thanks a million.

  20. why has nobody been on in 8 years

    • avatar
    • T2P
    • Sun 15 Aug 2010

    I can't understand. Can you send the completed example?

  21. I m designing my website in asp.net.

    I have embed code given above, but it is not working, and gives me following error when I click for search

    The resource cannot be found.

    Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

    Requested URL: /index.aspx.nsf/All

    plz tell me its solution asap.

    a bundle of thanks in advance

  22. Can someone please tell me how can i add a search box in my website which will search the page of my website only. I need this very much!

    • avatar
    • Nikola
    • Tue 2 Nov 2010

    Can someone please tell me how can i add a search box in my website ''which will search the page of my website only''. Please help me guys, I need this very much!

    • avatar
    • Nikola
    • Tue 2 Nov 2010

    Can someone please tell me how can i add a search box in my website ''which will search the page of my website only''. Please help me guys, I need this very much!

    Sorry for multiple posts, I needed to give email too, but it posted automatically after pressing enter :)

    • avatar
    • John
    • Mon 14 Feb 2011

    I have placed the search field in a separate form which display in the left navigation frame and removed query fields from seach form and $$SearchView for search still query value is blank. Somehow it is not getting s.value to do the search.

    function doSearch( s ) {

    var regExp1 = /\bfield\b/;

    var regExp2 = /[(,),<,>,\[,\]]/;

    var str = s.value; if ( str == "" ){

    alert("Please be sure to enter something to search for.");

    s.focus();

    } else {

    if ( typeof regExp1.source != 'undefined' ) //supports regular expression testing

    if ( regExp1.test( str ) || regExp2.test( str ) ){

    var alrt = "Please note that you can not include:";

    alrt += "\n\nThe reserved word 'field'\nthe characters [, ], (, ), < or >";

    alrt += "\n\nin your search query!\n\nIf you are confident that you know";

    alrt += "\nwhat you are doing, then you can\nmanually produce the URL required."

    s.focus();

    return alert( alrt );

    }

    openDbRelativeURL("Search2?SearchView&Query=" + s.value, parent.frames["DataFrame"]);

    }

  23. Thank you so much..

    This great and usefull..

  24. Hy! I want a search engine results page, but i wanted to do a search within my website, where after a user types in keywords in the searchbox, the results would be displayed on another page, but still within my website. Thanks again though. Can you help?? I'm searching the internet for 2 days an all can find is use google or use bing for a search .Thank you.

  25. I don't know if you still check on this, but I sure hope so. I'm trying to implement your search using the simple doSearch function (at this point). I'm checking the value of "s" with an alert box, ("s: " + s.value), and it's coming back undefined. Why isn't it capturing the value of the query field?

    • avatar
    • Avin
    • Wed 21 Sep 2011

    Hi!

    I am working on a project for my B.tech . It works on netbeans.

    I have some string values in an array on action.java page.

    i want to get all the data of Array on a different display.jsp

    page and print them with thier qrder..

    I am a beginner and don't know how to do it...

    Plzzz help me !!!!!

    • avatar
    • judderdude
    • Sun 20 May 2012

    What would be really great for a numpty like myself is if you could provide an html page with all this code in already so that I could reverse engineer it.

    • avatar
    • daveg
    • Tue 17 Jul 2012

    Hi All,

    I am really new at this and am trying to add a search box to my website, the code that I have creates the search box but for whatever reason the actual search function is not working any advise? Below is my code:

    Quick Search Start

    <form action="" id="Search"><div class="indent"><div class="rowElem1"><a href="#" onClick="document.getElementById('Search').submit()" class=" fright alignMiddle"><img alt="" src="images/button.gif" /></a><input type="text" class="input" value="Quick Search..." onBlur="if(this.value=='') this.value='Quick Search...'" onFocus="if(this.value =='Quick Search...' ) this.value=''" /></div></div>

    </form>

    Quick Search End

    Any help would be greatly appreciated!!

  26. Not getting the object s? It's always null. This just doesn't work. I've followed it to the letter. We're looking for an alternative to XPages by going back to basics, but we just can't get this to work.

Your Comments

Name:
E-mail:
(optional)
Website:
(optional)
Comment:



Navigate other articles in the category "Forms"

« Previous Article Next Article »
Storing lots of input fields in one list   Ideas on reporting form validation errors

About This Article

Author: Jake Howlett
Category: Forms
Keywords: search; input; path;

Options

Feedback
Print Friendly

Let's Get Social


About This Website

CodeStore is all about web development. Concentrating on Lotus Domino, ASP.NET, Flex, SharePoint and all things internet.

Your host is Jake Howlett who runs his own web development company called Rockall Design and is always on the lookout for new and interesting work to do.

You can find me on Twitter and on Linked In.

Read more about this site »