Single field searching

Single field searching is a way to search data (at server) on one field at a time. When using this method we construct a modal form where the user can select a field and condition to apply the search.  Singe Field serching

This method uses the url to post the search data and differ from the custom and toolbar search methods. The difference is that the posted search data is not in pair name:value. See below how data is posted.

Installation

In order to use this method the following modules should be included when downloading the grid: Common, Form Edit, Filter Plugin. For more information refer to Download

Calling Conventions

<script>
... 
jQuery("#grid_id").searchGrid( options );
...
</script>

or using the new API

<script>
... 
jQuery("#grid_id").jqGrid('searchGrid', options );
...
</script>

Where

  • grid_id is the id of the already constructed grid
  • options is an array of settings in name: value pairs format.

Typically when this method is called it launches the modal dialog and makes the grid inaccessible until the dialog is not closed.
This method is the default search method in the navigator if the search is enabled. The search parameters in navigator can be set the same way as the options described below.

<script>
...
jQuery("#grid_id").jqGrid({
...
   pager : '#gridpager',
...
}).navGrid('#gridpager',{view:true, del:false}, 
{}, //  default settings for edit
{}, //  default settings for add
{},  // delete instead that del:false we need this
{search_options}, // search options
{} /* view parameters*/
);
...
</script>

By default the dialog appears at upper left corner of the grid.

We add a new option overlay (default 10) in search dialog. If set to 0 the cover overlay is disabled and the user can interact with the grid.

Options

This method uses the following properties from language file grid.locale-xx and the can be passed in the options array of the serch method

$.jgrid = {
...
   search : {
     caption: "Search...",
     Find: "Find",
     Reset: "Reset",
     odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain']
   },
...
OptionTypeDescriptionDefault
afterShowSearchfunctionThis event fires (if defined) every time after the search dialog is shownnull
beforeShowSearchfunctionThis event fires (if defined) every time before the search dialog is shownnull
closeAfterSearchboolean If set to true this closes the search dialog after the user apply a search - i.e. click on Find buttonfalse
closeAfterResetboolean If set to true this closes the search dialog after the user apply a reset - i.e. click on Reset buttonfalse
dragbooleanEnables or disables draging of the modaltrue
jqModalbooleanIf set to true uses jqModal plugin (if present) to creat the dialogs. If set to true and the plugin is not present jqGrid uses its internal function to create dialogtrue
resizebooleanEnables or disables resizing of the modaltrue
modalbooleanIs set to true the search dialog becomes modalfalse
width integerDefines the width os the search dialog 450
height mixed Defines the height of the search dialog auto
top integerthe initial top position of modal dialog. The default value of 0 mean the top position from the upper left corner of the grid. When jqModal option is true (see below) and jqModal plugin is present any value different from 0 mean the top position from upper left corner of the window.0
left integerthe initial left position of modal dialog. The default value of 0 mean the left position from the upper left corner of the grid. When jqModal option is true (see below) and jqModal plugin is present any value different from 0 mean the left position from upper left corner of the window.0
captionstringThe caption of the modalsee lang file
showQuery boolean If set to true shows the query which is generated when the user defines the conditions for the search. Valid only in advanced search. Again with this a button near search button appear which allows the user to show or hide the query string interactively false
searchOnEnter booleanDetermines whether search should be applied on pressing Enter key. false
FindstringThe text in the find buttonsee lang file
multipleSearchbooleanIf set to true this activates the advanced searchingfalse
multipleGroupbooleanIf set to true this activates the advanced searching with a possibilities to define a complex conditions false
odataarrayTranslation strings that corresponds to the sopt optionssee lang file
onClosefunctionIf defined this event fires when the dialog is closed. Can return true or false. If the event return false the dialog will not be closednull
afterRedraw function This function if defined is lunched every time the filter is redrawed - the filter is redrawed every time when we add or delet rules or fields Tio this function we pass the search parameters as parameter null
onSearchfunctionIf defined this event fires when the search Button is clicked.null
onResetfunction If defined this function fire if reset button is activated null
closeOnEscape boolean If this option is set to true the search dialog will be closed if the user press ESC keyfalse
onInitializeSearchfunctionThis event occurs only once when the modal is creatednull
recreateForm boolean when set to true the form is recreated every time the search dialog is activated with the new options from colModel (if they are changed)false
showOnLoadboolean This option is valid only in navigator options. If set to true the dialog appear automatically when the grid is constructed for first time false
errorcheck boolean if searchrules are defined this turn on of error checking. If there is a error in the input the filter is not posted to the server and a error message appear.true
ResetstringThe text for the clear (reset) buttonsee lang file
sFieldstringSee sopt descriptionsearchField
sFilterstringAplicable to advanced searching. See advanced searching filters
sOperstringSee sopt descriptionsearchOper
soptarrayUse this option to set common search rules. If not set all the available options will be used. All available option are: ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc','nu','nn'] The corresponding texts are in language file and mean the following: ['equal','not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain','is null','is not null'] Note that the elements in sopt array can be mixed in any order.
sValuestringSee sopt descriptionsearchString
overlayintegerIf this option is set to 0 the overlay in grid is disabled and the user can interact with the grid while search dialog is active 10
layer string If defined this should be a valid id in the DOM. Also if this option is set the filter is inserted as child of this element null
tmplNames array Defines the name of the templates used for easy user input - by example like this : ['Template1', 'Template2',…]. See grid demo how to define templates. null
tmplFiltersarray of objects if defined this should correspond to the tmplNames. See demo how to define template null
tmplLabel string If a template is defined a select element appear between the Reset and Find buttons. This is a the text describing the select Template:
zIndexintegerThe starting z-index for the dialog. If you will see the dialog form under another elements or dialogs you should use the parameter with some value higher as default value 950. In the most cases it should be the value higher as 1000 - the default value of jQuery UI dialog.950

As mentioned above posting search data differs from custom and toolbar searching. When the find button is clicked, jqGrid adds three parameters to the url (again with _search=true), in name=value pairs:

  • sField: the 'searchField', the value comes from the index in colModel
  • sValue: the 'searchString', the value is the entered value
  • sOper: the 'searchOper', the value is the type of search - see sopt array

For example if the field index is invid, operation is equal, and the searched value is 123, then the string that is posted to the server look like:

http://localhost/demo35/server.php?...&searchField=invid&searchString=123&searchOper=eq

colModel Options

As of 3.5 release jqGrid uses a common search options that can be used on every search method. Below is a list of these options that should be set in colModel. Note that some options are not applicable for particular method.

OptionTypeDescriptionDefault
searchbooleanDetermines if the field can be searched.true
stypestringDetermines the search type of the field. Can be text - also a input element with type text is created and select - a select element is createdtext
searchoptionsobject Object which contain definition, events and other properties for the searched field. See below
searchrulesobject Object which contain additional conditions for validating user input

The searchoptions object have the following properties:

The searchoptions are not applicable to custom search method. This method uses separate options.
PropertyTypeDescription
dataUrlstringThis option is valid only for the elements of type select - i.e stype:'select'. The option represent the url from where we load the select element. When this option is set the element will be filled with values from the ajax request. The data should be a valid html select element with the desired options. By example the request should contain <select><option value=“1”>One</option> <option value=“2”>Two</option></select>. This is called only once.
buildSelectfunctionThis option have sense only if the dataUrl parameter is set. In case where the server response can not build the select element you can use your on function to build the select. The function should return a string containing the select and options value(s) as described in dataUrl option. Parameter passed to this function is the server response
dataInitfunctionIf set this function is called only once when the element is created. To this function we pass the element object.
dataInit: function(elem) {
do something
}
Also use this function to attach datepicker, time picker and etc. Example:
dataInit : function (elem) {
$(elem).datepicker();
}
dataEventsarrayList of events to apply to the data element; uses $(“#id”).bind(type, [data], fn) to bind events to data element. Should be described like this:
dataEvents: [
{ type: 'click', data: { i: 7 }, fn: function(e) { console.log(e.data.i); }},
{ type: 'keypress', fn: function(e) { console.log('keypress'); } }
]
attrobjectattr is object where we can set valid attributes to the created element. By example:
attr : { title: “Some title” }
Will set a title of the searched element
searchhiddenboolean By default hidden elements in the grid are not searchable . In order to enable searching when the field is hidden set this option to true
soptarrayThis option is used only in advanced , single and toolbar field searching and determines the operation that is applied to the element. If not set all the available options will be used. When used in toolbar searching the first element is used. All available option are:
['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
The corresponding texts are in language file and mean the following:
['equal','not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain']
Note that the elements in sopt array can be mixed in any order.
defaultValuestringIf not empty set a default value in the search input element.
valuemixed The option is used only for stype select and defines the select options in the search dialogs. When set for stype select and dataUrl option is not set, the value can be a string or object.
If the option is a string it must contain a set of value:label pairs with the value separated from the label with a colon (:) and ended with(;). The string should not end with a (;)- editoptions:{value:“1:One;2:Two”}.If set as object it should be defined as pair value:name - editoptions:{value:{1:'One',2:'Two'}}
clearSearchbooleanWhen set to false the X icon at end of search field which is responsible to clear the search data is disabled. the default value is true
Note: when the dataUrl in searchoptions object is not used for the search type select, the definitions for the select are taken first from searchoptions value property and if this is not defined a editoptions value property is used- i.e editoptions:{value:“1:one;2:two”,…}. See below how to use these options in different search methods.
2018/01/14 15:02

colModel conventions:

<script>
jQuery("#grid_id").jqGrid({
...
   colModel: [ 
      ... 
      {name:'price', index:'price', width:60, search:true, stype:'text', searchoptions:{dataInit:datePick, attr:{title:'Select Date'}} },
      ...
   ]
...
});
datePick = function(elem)
{
   jQuery(elem).datepicker();
}
</script>

searchrules

This option add additional properties to the searchable element and should be used in colModel. Mostly it is used to validate the user input before submitting the value(s) to the server. Syntax:

<script>
jQuery("#grid_id").jqGrid({
...
   colModel: [ 
      ... 
      {name:'price', ..., searchrules:{required:true....}, search:true },
      ...
   ]
...
});
</script>

Below is the list of available options:

OptionTypeDescription
requiredboolean (true or false) if set to true, the value will be checked and if empty, an error message will be displayed.
numberboolean (true or false) if set to true, the value will be checked and if this is not a number, an error message will be displayed.
integerboolean(true or false) if set to true, the value will be checked and if this is not a integer, an error message will be displayed.
minValuenumber(integer)if set, the value will be checked and if the value is less than this, an error message will be displayed.
maxValuenumber(integer)if set, the value will be checked and if the value is more than this, an error message will be displayed.
emailbooleanif set to true, the value will be checked and if this is not valid e-mail, an error message will be displayed
urlbooleanif set to true, the value will be checked and if this is not valid url, an error message will be displayed
dateboolean if set to true a value from datefmt option is get (if not set ISO date is used) and the value will be checked and if this is not valid date, an error message will be displayed
timebooleanif set to true, the value will be checked and if this is not valid time, an error message will be displayed. Currently we support only hh:mm format and optional am/pm at the end
customboolean if set to true allow definition of the custom checking rules via a custom function. See below
custom_funcfunction this function should be used when a custom option is set to true. Parameters passed to this function are the value, which should be checked and the name - the property from colModel. The function should return array with the following parameters: first parameter - true or false. The value of true mean that the checking is successful false otherwise; the second parameter have sense only if the first value is false and represent the error message which will be displayed to the user. Typically this can look like this [false,“Please enter valid value”]
“The searchrules will be used only in the searching dialog, but not in the searching filter…..” according to the following link by Oleg [http://stackoverflow.com/a/9011733]
Custom Checking example
<script>
function mypricecheck(value, colname) {
if (value < 0 || value >20) 
   return [false,"Please enter value between 0 and 20"];
else 
   return [true,""];
}
jQuery("#grid_id").jqGrid({
...
   colModel: [ 
      ... 
      {name:'price', ..., searchrules:{custom:true, custom_func:mypricecheck....}, search:true },
      ...
   ]
...
});
</script>
2018/01/14 15:02

Discussion

atefano Romoli Fenu, 2009/09/07 08:13

How to obtain the same result as the “cancel” button of the search dialog via my own script ?

Problem to solve: If i close the search dialog the grid continue showing the last result. If i want the grid to show all the records without any filters i need to reload the entire page or reopen the search dialog and use the clear button to reset the last search. I've tried to use the onClose event to reload grid but the post data of the search remain active: _search=true and filters=[…..] . So i tried to removePostDataItem(“filters”) and it seems to work but the _search variable remain true. Suggestions ?

Tony Tomov, 2009/09/07 08:25

Hello, The same way you remove the filters - just set (since you use postext module) search parameter to false (note - not _search). Something like setPostDataItem(“search”,false);

Stefano Romoli Fenu, 2009/09/07 12:51

I've tried but doesn't work ! In the way you suggest you set only another variable named “search” (not _search) ? In the PHP code, the check is made on _search. I could change the PHP code but before doing this i prefere to know if there is a way to change the value of the _search variable ? Since the “cancel” button of the search dialog do what i want, i think there is a function that was called by the button and i would like to refere to that function from my own script.

Ken, 2009/09/16 20:07

datepicker showing up behind search.

To ensure the datepicker is on top of the search, it is important to set the z-index to something high.

<style> .ui-datepicker {z-index:1200;} </style>

See this in action on the demo page http://www.trirand.com/jqgrid/jqgrid.html (page source, line 36)

Props to Schmitty who blogged this on http://blog.schmitty.me/?p=129

Diptendu Dutta, 2009/11/26 08:08

We need new option “ResetOnClose”

Most users expect the original grid data to display when they close the search dialog. Could we add a new option ResetOnClose with default value “true” to enable this behaviour.

Having to write code on OnCLose event and mucking around in postdata to achieve this effect seems too much.

fivesixcolor, 2010/04/15 03:41

We need new option “ResetOnClose”too

There is a option “closeAfterSearch” if set to true this closes the search dialog after the user click on Find button. But this wouldnot work after user click on Reset button. There no way to ResetOnClose by writing code.

Richard Fine, 2010/01/21 15:25

This doesn't work for clientside stuff, does it?

Peter Kleynjan, 2010/06/03 09:03

Re ResetOnClose / cancel button:

I guess it's not part of the official API, but I've found one thing that works (in 3.6.5 at least; “$” is my JQuery function):

resetFilter = function(){ $(”.ui-reset”).click(); };

inside the JQ function:

  $("#mygrid").searchGrid({ onClose: resetFilter } );

Feel free to set me straight it there is a better way… -Peter

Thibault, 2011/05/29 14:42

I have a problem with the Single field searching. The display is okay but when I click the Find button nothing happens. I feel he does not know where to look, or he gets no value .. Help!

Nicolas Machado, 2011/09/21 20:39, 2011/09/22 13:42

Hi, I have the same problem, I'm trying SINGLE search and nothing happens. I thing that the samples are incomplete, as I think that $where variable sould be completed with this values: $sField = $_GET['searchField']; $sValue = $_GET['searchString']; $sOper = $_GET['searchOper'];

Am I right ? Regards Hi Again, I added those variables to the ^PHP and it works, is a good idea that a snippet code should be added to the Documentation.

You could leave a comment if you were logged in.

QR Code
QR Code wiki:singe_searching (generated for current page)