Overview

QueryBuilder is an UI component to create queries and filters.
  • It can be used on advanced search engine pages, administration backends, etc.
  • It is highly customizable and is pluggable to many jQuery widgets like autocompleters, sliders and datepickers.
  • It outputs a structured JSON of rules which can be easily parsed to create SQL/NoSQL/whatever queries.
  • And it also comes with a set of great plugins and has a full events system for even more features.
But let's look at a live example !

The full code of this example can be found here.

Getting started

Download jQuery QueryBuilder

Dependencies

Don't want to use Bootstrap ?

Let's see what we can do for you.

Let's go!

Include query-builder.css in your page head and query-builder.js after the dependencies. Then add QueryBuilder to any <div> you want.

<div id="builder"></div>

<script>
  $('#builder').queryBuilder({
    filters: [ ... ]
  });
</script>

QueryBuilder can also be used with CommonJS :

require(['jquery', 'query-builder'], function($) {
  $('#builder').queryBuilder({
    filters: [ ... ]
  });
});

A standalone version is available with $.extendext and doT.js included (you still need to add jQuery and Bootstrap).

Backends

Awesome people implemented parsers in various language, check them out :

Usage

Options

Name type default description
filters object[] required Array of available filters in the builder. See below
plugins object Configuration of plugins. See plugins page
rules object Initial set of rules. It's like calling setRules method after initialization. By default the builder will contain one empty rule.
optgroups object List of groups in the filters and operators dropdowns (see filters and operators configuration). It can be a simple id => label map or contains localized strings. More details
default_filter string null The id of the default filter for any new rule.
sort_filters boolean|function false Sort filters alphabetically, or with a custom function (passed to Array.sort).
allow_groups boolean|int true Number of allowed nested groups. true for no limit.
allow_empty boolean false No error will be thrown is the builder is entirely empty.
display_errors boolean true When an error occurs on a rule, display an icon with a tooltip explaining the error.
conditions string[] ['AND', 'OR'] Array of available group conditions. Use the lang option to change the label.
default_condition string 'AND' Default active condition.
inputs_separator string ' , ' Piece of HTML used to separate multiple inputs (for between operator).
display_empty_filter boolean true Add an empty option with select_placeholder string to the filter dropdowns. If the empty filter is disabled and no default_filter is defined, the first filter will be loaded when adding a rule.
select_placeholder string '------' Label of the "no filter" option.
operators object[] Configuration of operators. See below
lang_code string 'en' One of the language files code available. Default is English or the last loaded language.
lang object Additional/overwrites translation strings. See below
icons object glyphicons Font-icons used in the builder. Defaults to using Glyphicons. See below
templates object HTML templates. See below

Filters

The filters option is an array of plain objects defining the rules possible contents. Here are the available attributes:

Name type default description
id string required Unique identifier of the filter.
field string =id Field used by the filter, multiple filters can use the same field.
label string =field Label used to display the filter. It can be simple string or a map for localization. More details
optgroup string|object Optional id of an <optgroup> in the filters dropdown. If the optgroup does not exist in the global optgroups map, it will be created with label=id for all languages.
type string required Type of the field. Available types are string, integer, double, date, time, datetime and boolean.
input string|function 'text' Type of input used. Available types are text, textarea, radio, checkbox and select.
It can also be a function which returns the HTML of the said input, this function takes 2 parameters:
  • rule a Rule object
  • input_name the name of the input
values array|object required* Required for radio and checkbox inputs. Generally needed for select inputs. More details
value_separator string Used the split and join the value when a text input is used with an operator allowing multiple values (between for example).
default_value mixed As it says :-)
input_event string 'change' Space separated list of DOM events which the builder should listen to detect value changes.
size int Only for text and textarea inputs: horizontal size of the input.
rows int Only for textarea inputs: vertical size of the input.
multiple boolean false Only for select inputs: accept multiple values.
placeholder string Only for text and textarea inputs: placeholder to display inside the input.
vertical boolean false Only for radio and checkbox inputs: display inputs vertically on not horizontally.
validation object Object of options for rule validation. See below
operators array Array of operators types to use for this filter. If empty the filter will use all applicable operators. Show all operators
plugin string Name of a jQuery plugin to apply on the input.
plugin_config object Object of parameters to pass to the plugin.
data object Additional data not used by QueryBuilder but that will be added to the output rules object. Use this to store any functional data you need.
valueSetter function Function used to set the input(s) value. If provided the default function is not run. It takes 2 parameters:
  • rule the Rule object
  • value
valueGetter function Function used to get the input(s) value. If provided the default function is not run. It takes 1 parameter:
  • rule the Rule object

Validation

QueryBuilder integrates a configurable validation system triggered when validate() or getRules() methods are called. The default validator checks for emptyness and can be extended with format check and bounds.
Optionally you can define a custom validation callback.

Here are the available attributes of the validation field of each filter:

Name type description
format string|object
  • For date, time, datetime: a valid MomentJS string format
  • For string: a regular expression (plain or RegExp object)
min integer|double|string
  • For integer, double: minimum value
  • For date, time, datetime: minimum value, respecting format
  • For string: minimum length
max integer|double|string
  • For integer, double: maximum value
  • For date, time, datetime: maximum value, respecting format
  • For string: maximum length
step integer|double
  • For integer, double: step value (for double you should always provide this value in order to pass the browser validation on <number> inputs).
    any is allowed to bypass browser validation.
messages object Custom error messages for the standard validations, keys are validation names.
validation: {
  format: /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/,
  messages: {
    format: 'The provided IP is not valid'
  }
}
allow_empty_value boolean true to allow empty user input for this filter
callback function A function used to perform the validation. If provided, the default validation will not be performed. It must returns true if the value is valid or an error string otherwise. It takes 2 parameters:
  • value
  • rule the Rule object

Methods

The plugin's function acts as a proxy to access all underlying methods.

$('#builder').queryBuilder('methodName', param_1, param_2);

You can also execute methods by getting a reference to the builder instance.

$('#builder')[0].queryBuilder.methodName(param_1, param_2);

Only main methods are described.

Plugins methods

Methods added by plugins are detailed in their respective sections.

.validate()

Returns a boolean indicating whether the builder is valid or not. Use the validationError event to catch per-rule validation errors. If display_errors is enabled the invalid rules will turn red.

.getRules([options])

Performs validation and returns the rules as a plain JSON object. See the demo for output example. The method takes an optional object of options.

Option type default description
get_flags boolean|string false true to return rule and group flags that differ from the default values. 'all' to return all rule and group flags.
allow_invalid boolean false true to return the rules evn though the validation fails. The returned object has an additional `valid` property.
// get all rules
$('#builder').queryBuilder('getRules');

// get all rules and their flags when applicable
$('#builder').queryBuilder('getRules', { get_flags: true });

Other formats

For other output formats like SQL and MongoDB, please refer to the plugins page.

.setRules(rules [, options])

Clears the builder and sets new rules. The parameters must have the same structure as the output of getRules. See an example

Option type default description
allow_invalid boolean false true to allow loading invalid and/or incomplete rules (no operator, no value, etc.).
$('#builder').queryBuilder('setRules', { ... });
User data

Each rule and group can have an additional data parameter which will be merged with the filter data (for rules only) when calling getRules.

$('#builder').queryBuilder('setRules', {
  condition: 'AND',
  data: { // group data
    foo: 'bar'
  },
  rules: [
    {
      /* rule definition */
      data: { // rule data
        foo: 'bar'
      }
    }
  ]
});
The rule's data will be removed if the filter of the rule is changed. You can use the flags (see bellow) to lock the filter of a rule.
Empty rules

The setRules method will throw an error if a rule has no filter. If for some reason you want to populate the builder with an empty rule, use the empty keyword.

$('#builder').queryBuilder('setRules', {
  condition: 'AND',
  rules: [
    {
      /* standard rule */
    },
    {
      /* empty rule */
      empty: true
    }
  ]
});
Flags

Each rule can have an additional flags parameter which will control the editability of the rule.

Property type default description
filter_readonly boolean false The filter select box is disabled.
operator_readonly boolean false The operator select box is disabled.
value_readonly boolean false The value inputs are disabled.
no_delete boolean false The rule can't be deleted. A group containing an undeletable rule can't deleted.

Alternatively you can set the readonly parameter to true, which is a shorthand to:

{
    filter_readonly: true,
    operator_readonly: true,
    value_readonly: true,
    no_delete: true
}

The same way, each group can have an additional flags parameter which will control the editability of the group.

Property type default description
condition_readonly boolean false The group condition can't be changed.
no_add_rule boolean false The "Add rule" button is disabled.
no_add_group boolean false The "Add group" button is disabled.
no_delete boolean false The group can't be deleted.

Alternatively you can set the readonly parameter to true, which is a shorthand to:

{
  condition_readonly: true,
  no_add_rule: true,
  no_add_group: true,
  no_delete: true
}

.getModel([element])

Given a group or rule DOM element, returns the associated Group or Rule object. Useful to perform manual operations on the builder (see Inside the box). Without parameters it returns the root group model.

var root_model = $('#builder').queryBuilder('getModel');

var last_node_model = $('#builder').queryBuilder('getModel', $('#builder .rule-container').last());

.reset()

Removes all rules.

$('#builder').queryBuilder('reset');

.destroy()

Completely destroy the builder and it's data.

$('#builder').queryBuilder('destroy');

Events

QueryBuilder uses events to notify the "outer world" about various things happening, like adding a rule or when a validation error happens. The events system is also used by plugins.

Read more about events

Themes

QueryBuilder comes with two colors-schemes: default (clear) and dark. Change the active theme by switching stylesheets. You cannot use both color-schemes on the same page.

Advanced

Operators

QueryBuilder is bundled with an extensive list of operators. You can change which operators are available for each filter (see filters configuration) but you can also modify/reorder the operators globally and even add new custom operators.

The operators config property is an array of strings (existing operators) or object (existing and new operators). The operators properties are :

Property type description
type string Identifier of the operator, use the lang.operators to translate or give a human readable name to your operator.
optgroup string Optional id of an <optgroup> in the operators dropdown. If the optgroup does not exist in the global optgroups map, it will be created with label=id for all languages.
nb_inputs int The number of inputs displayed. Typical values are 0 (is_null & similar operators), 1 (most operators) and 2 (between operator).
multiple boolean Inform the builder that each input can have multiple values. true for in, bot_in, false otherwise.
apply_to array An array containing string, number, datetime, boolean.

For example to only use "equal" and "not equal" operators you use this config :

operators: ['equal', 'not_equal']

To use "equal" and "not equal" and a custom operator, in custom optgroups :

operators: [
  { type: 'equal', optgroup: 'basic' },
  { type: 'not_equal', optgroup: 'basic' },
  { type: 'geo', optgroup: 'custom', nb_inputs: 3, multiple: false, apply_to: ['number'] }
]

Translation

Translation files are available in the i18n folder. Just include one of the files after the main JavaScript to use it.

You can load multiple translation files and use the lang_code option to choose which language to use.

Available languages are (some are partially translated) :

Albanian Arabic Azerbaijani Bulgarian Simplified Chinese Czech Danish Dutch English Farsi French German Greek Hebrew Italian Norwegian Polish Portuguese Brazilian Portuguese Romanian Russian Spanish Turkish Ukrainian

Alternatively you can overwrite some translations with the lang option. It is very useful for custom operators and conditions.
Default English strings are in the source code .

Icons

The icons option provides a way of using alternate icons sets. Available attributes:

Name type default
add_group string 'glyphicon glyphicon-plus-sign'
add_rule string 'glyphicon glyphicon-plus'
remove_group string 'glyphicon glyphicon-remove'
remove_rule string 'glyphicon glyphicon-remove'
error string 'glyphicon glyphicon-warning-sign'

Templates

For very specific customizations, QueryBuilder provides a way to completely overwrite the HTML templates used to display rules and groups. It uses the doT.js template engine by default, but can be used with most JS template engines, like underscore.js one.

Very advanced feature

Modifying templates can lead to a non-functionnal builder if the general layout differs too much. In particular, non-Bootstrap CSS classes should not be removed.

Templates can be provided as a doT.js template string or as a function taking an object of variables and returning an HTML string (_.template for instance). Check the default templates in the source code.

For all templates, these variables are available :

  • builder reference to the QueryBuilder object
  • settings short-hand for builder.settings
  • lang short-hand for builder.settings.lang
  • icons short-hand for builder.settings.icons

group

The template used to build an empty group. Other variables available :

  • group_id unique identifier of the group
  • level level of the group (1 is root)
  • conditions the conditions available in this group

rule

The template used to build an empty rule. Other variables available :

  • rule_id unique identifier of the rule

filterSelect

The template used to build the filters selectbox. Other variables available :

  • rule a Rule object
  • filters the filters available in this rule
  • translate a function used for localization

operatorSelect

The template used to build the operators selectbox. Other variables available :

  • rule a Rule object
  • operators the operators available in this rule
  • translate a function used for localization

Inside the box

You might have noticed that callbacks and events refer to two objects Rule and Group. These objects are part of the data model with partial data-binding used internally by QueryBuilder. Here are the structures of these two objects. Most attributes will live-update the builder when modified.