filter.js – Client side search filtering using JSON and jQuery

Speed for search result filtering is critical. Its fine for site users to wait for some time (maybe a few seconds) to load the search results but after that filtering better be fast otherwise people lose interest.

To give a simple example of how things are not user friendly is if you go to or Its frankly appalling! For every click and every selection, the entire page refreshes. Though its good for showing Ad impressions (which I hate) when browsing an e-commerce site, the usability is lost.

On the other hand, have a look at or and it tells a different story. They fire Apis to their server to get json data and render that via Javascript. Usability is excellent. (no wonder they are doing so well!)

We did client-side search filtering in a couple of portals we built and realized that we should generalize this. That got us started and we ended up with filter.js This is a Javascript module that we have tried and tested on various portals.

Some key features are:

  • Category and sub-category based filtering
  • Slider based filtering
  • Trigger on any HTML element.
  • Date filtering (in process)

To use filter.js is simple. Add this to your <head> section:

<script src="" type="text/javascript"></script>

There are dependencies on how to render HTML components. Currently, its our own custom code but we have plans to upgrade this to integrate  with mustache or handlebars. For now, we live with it 😉

Defining the search criteria and the JSON objects

You can generate JSON data in any way you wish. Remember that the top-level entity will be used for rendering the view – in this case ‘person’.

var people = [{person: {name: 'Jiren', age:26, country: 'India', country_id: 1,
                        states : [{ state : 'MH', state_id : 3 },
                                  {state : 'HN', state_id : 4}] } },
              {person: {name: 'Joe', age:25, country: 'USA', country_id: 2,
                        states : [{ state : 'MH', state_id : 3 },
                                  {state : 'HN', state_id : 4}] } }

Defining the view function

We have some custom code for rendering HTML components. This assumes that you have the json objects in place. Here is an exmaple:

var view = function(person){
    name = this.span({'class': 'name'},;
    age = this.span({'class': 'age'}, person.age);
    country = this.div({'class': 'country'},;
    return'/demo/' + ,{'title':}, [name,age,country]);

A more detailed example is available in the examples given on github. To define the filter criteria, all you need to do is pass a combination of the HTML components, the events and the JSON object attributes. For example:

var settings = {
  filter_criteria: {
    country: ['#country_list input:checkbox .SELECT.:checked', 'country_id'],
    age: ['#age_list input:checkbox .SELECT.:checked .TYPE.range', 'age'],
    price: ['#price_filter .EVENT.change .SELECT.:input .TYPE.range', 'timeleft']
    states: ['#state_list input:checkbox .SELECT.:checked', 'states.ARRAY.state_id'],

/* Trigger the filtering */
var fJS = new filterJS(people, "#people_list", view, settings);

Here is how this works:

Category based filtering

['#country_list input:checkbox .SELECT.:checked', 'country_id']

All the checkboxes under the <div id=country_list> are used as the selectors. When the checkbox click event is triggered for any checkbox, all the checked check-boxes are used as the filter criteria and the JSON objects which match the ‘country_id‘ will be rendered using the view function. Rendering is done only once and then the display is toggled as needed.

Range based filtering via checkbox

age: ['#age_list input:checkbox .SELECT.:checked .TYPE.range', 'age']

Its exactly the same as shown earlier except for the  additional .TYPE.range attribute. This tells the filter.js that it needs to pick up the range from the HTML element for filtering. This is typically added like this:

<div id='age_list'>
  <input type='checkbox' value="below-30">
  <input type='checkbox' value="30-50">
  <input type='checkbox' value="50-above">

So, now the filtering will trigger on the the range of age – this can be customized as you wish. Note the boundary limiters ‘below-30′ and ’50-above’.

Range based filtering via slider

price: ['#price_filter .EVENT.change .SELECT.:input .TYPE.range', 'timeleft']

Here the slider id change event triggers the filter and the value of the slider is used to filter the JSON data. Here is the sample HTML code. Ensure that you have jquery-ui.js included in the header.

<script type="text/javascript">
  $( "#price_slider" ).slider({
     min: 0,
     max: 1000,
     values:[0, 500],
     step: 5,
     slide: function( event, ui ) {
       $( "#price_range_label" ).html('$' + ui.values[ 0 ] + ' - $' + ui.values[ 1 ] );
       $('#price_filter').val(ui.values[0] + '-' + ui.values[1]);
<span id="price_range_label">$0-$100</span>
<div id="price_slider"></div>
<input type="hidden" id="price_filter"/>

Demo Time

Have a look at and to see filter.js in action in 2 different scenarios!

Alternatively, you can also clone the github repository and see the demos/filterjs.html

We look forward to some feedback from you and hopefully some contributions!

Filter away!


Thanks for the overwhelming response! I have added mustache templating for rendering the HTML view snippets.

Define mustache.js template in html page.

<script id="person_template" type="text/mustache">
<a href="/demo/{{id}}" title="{{name}}">
<span class="name">{{name}}</span>
<span class="age">{{age}}</span>
<div class="country">{{country}}</div>

View function:

var mustache_template = $("#person_template").html(); //Find template data.
var mustacheView = function(person){
return Mustache.to_html(mustache_template, person);
This entry was posted in Javascript and tagged , , . Bookmark the permalink.

320 Responses to filter.js – Client side search filtering using JSON and jQuery

  1. Amol Pujari says:

    we tried similar rules on one of given assignments….
    – as mush as possible have minimum data exchanged between browser and server
    – make use of js, json to hold any temporary data to be used on triggers
    – keep data loaded(json) when you know for sure that its going to be triggered

  2. Looks great. I wonder how /where/if you incorporate ajax-calls to the server to get the new set of JSON-objects which satisfy the new filter-constraints. Is this generalized in any way?

    • jiren says:

      Good point. I made the changes and updated on git version 1.1 for event unbinding and again apply new filter criteria.

      So, you can fetch the new JSON object from the normal AJAX request and then do the following:
      $(‘#service_list’).html(”); // clear html target list.
      fJS = filterInit();

      See the demo for the above reference.

  3. Pingback: Client Side Search Filtering using JSON and jQuery: Filter.js | Greepit

  4. Hanumakanth says:

    will it supports for pagination results too?

  5. jiren says:

    filter.js is not supporting the pagination. Pagination defeats the purpose of search filter on client side.

    • Muhammad says:

      Thank you for your great tool but I don’t understand how to getearne the json by using Ajax requests so as to get the data from the database. I want to seach into a database of thousands of people and select them according to some criteria. I cannot load all the data when loading the page.Can you show us an example of code that communicates with a database through Ajax/jQuery so as to getearne the json? Thanks a lot, it will serve a lot of people.

  6. Umesh Maurya says:

    Can we use this with jquery templates ?

    • jiren says:

      Yes, you can use jquery template.
      In view function return $.tmpl(template, json object)
      Json object is view function arg

  7. Pingback: These are a few of my favourite things – Part I (Javascript) « Solutionware – Passionate about the Web

  8. Sreepathi says:

    I am trying to replicate the function of the check box with a link, but not sure how to do that. I have even tried to fire the click event of the check box on clicking the link but I did not have much success on that. Please suggest me if I am missing something.

    • jiren says:

      First, link is not a html input element, so it has no value. Therefor you have to define hidden field for that and apply filter on it like slider(in demo). i.e HTML: Price: 100 – 200

      Set filter criteria on hidden field filter_criteria: { linkfilter: [‘#link_filter .EVENT.change .SELECT.:input .TYPE.range’, ‘amount’] }

      Bind event on link: $(‘#filter_by_link’).click(function(e){ e.preventDefault(); fJS.filter(); // fJS is filter.js object. });

      Also I am going to update demo for this.

      • Sreepathi says:

        Thanks for the reply. My situation is something like I have different categories of filter like date range and status types(note that this is not a range) and all these filtering has to be done on click of the link rather than check boxes. I somehow managed to achieve it through a combination of link filter in the demo for date range filter and using hidden check boxes on clicking the link for status type to filter the data. Please suggest if what I have done is the best solution. Also I have to do sorting of the filtered search results. Is there a way to combine sorting and filtering.

      • jiren says:

        I updated demo and readme for filter using link. There is example of range filter using link. You can also use for single value by setting data-value of link.

      • jiren says:

        Hidden field is better option then hidden checkbox. For sorting you can use any jquery sorting plugin like jqery.tinysort.js

      • Toby says:

        Hi jiren,
        is it possible to do a range filter with a non-hidden input field? That means, in the input field you type in only the maximum-number. Then it shall be filtered: 0 to maximum-number (below-‘maximum-number’).

    • jiren says:

      Hi Toby
      Filtering logic return only for single input, so we can’t merge two input value and make single filtering criteria.So currently you have to add hidden input and change value when text input or other input value change.

      • Toby says:

        Thank you for your answer. But I asked for one input value only. And I need to filter for the range between 0 and the input value. Is this possible?

    • jiren says:

      Yes this is possible. You can update hidden field value like 0-(your inout value).Make 0 as fixed value. You can check link filter code in example(filterjs.js – line:39) for updating hidden field value and applying filter.

      • Toby says:

        Thank you once again for your kind replay. Unfortunately it’s not working when I tried this:


        var urange = “0-“+$(this).data(‘value’);

        filter_criteria: {
        u: [‘#u_filter .EVENT.change .SELECT.:input .TYPE.range’, ‘variable’],

        It would be great if you could help.

      • jiren says:

        Can you send me your html and javascript(just save page from browser and zip it), so I can check it and let you know.

  9. Sri says:

    Thanks for the great article. I have created search results filter following the example above, however I have few questions. In my case the filter links will be created dynamically based on the search results. Also I can select only one filter per category. When I select a filter on category 1 I need to update the filters in other category. For eg. consider the scenario. Category A > Filter A1(5), Filter A2(3) Category B> Filter B1(2), Filter B2(4), Filter B3(2) and if I select Filter A1, Filter A2 should be hidden and filters under Category B will look like Filter B1(1), Filter B2(4). And if I unselect the I should update the other categories and filters accordingly. My initial idea to solve this is to get hold of the filtered JSON data so that I can redraw the filters even though I do not know how to get hold of it at this time. Remember the filters are initially created and rendered dynamically from the search results JSON. So if I can get hold of the filtered JSON I can pass it as an argument to the same function and re render the updated filters. I would appreciate any suggestions in this regard.

    Thank you,

    • jiren says:

      You can access filtered JSON data using registering callback, for this pass functions in ‘settings’. Each callback call after filtering event, here ‘result’ is filtered JOSN data.
      var filter_callbacks = {
      logger: function(result){
      $.each(result, function(i,v){ console.log(})
      var settings = {
      filter_criteria: {
      country: [‘#country_list input:checkbox .SELECT.:checked’, ‘country_id’]},
      callbacks: filter_callbacks


    • jiren says:

      You can find example for this on github(

    • rminkara says:

      Thanks for your reply. But am not clear on how you modify the datasource.
      I understand that we need to add a parent object “product” to the string, but how can we accomplish that?
      Many thanks

      • jiren says:

        You don’t have to modify datasource, you can generate json using root name. In your case root name is product for each product record in JSON.

      • rminkara says:

        Thank you for your reply. Perhaps you can shed more light on my situation.
        I am using ASP JSON Helper (Jsnon.Encode) to generate the JSON. The problem is that the string comes out with no root object. How can I use a JS forloop to add the root to the JSON string.
        My JSON string looks something like this:

  10. Seb says:

    Thank you for your great work!

    Two questions:
    – Is it possible to string together single values for link filtering? Like for example 31 and 34? (and
    maybe have it also check the corresponding checkboxes?)
    – Can I change the filter behaviour, so that all results are shown if no boxes are checked?

    Any help would be greatly appreciated!

    Thanks again,

    • jiren says:

      Yes, you can set link input like(ref: examples/filterjs.html and examples/filterjs.js )

      <a id="filter_by_link" href="#" data-value="50" data-target='#link_filter'>Price: 50 </a>
      <input type="hidden" id="link_filter" value="50" />

      Set the ‘filter_criteria’:
      link_filter: ['#link_filter .EVENT.change .SELECT.:input', 'amount']

      To set corresponding checkboxes you have to implement code in the click event.
      // corresponding checkbox selection implementation

      For second point you can set ‘and_filter_on: false’ in filter criteria
      but implemented ‘and’ – ‘or’ filter function is not working correctly , I am working on it.
      On complete i will let you know.

  11. Seb says:

    Thanks for your quick reply and help!

    I know how to filter by link with an amount like 30-50, but can I also string together different single values or ranges? Like “30-50″+”green”+”c” to give users a number of filter presets?

    Best regards,


    • jiren says:

      This is a good idea. I have not done this yet. Do submit a pull request if you do this. I shall try to do this when I get some free time.

  12. jcd3 says:

    hiya – awesome tool!
    is it possible to pull json data from an externally hosted file? how do you do this?

    • jiren says:

      Yes, it is possible. You can get json file data and add to tag.

      $.get(‘test.json’, function(data){

  13. Hawks says:

    Thank you for your great tool but I don’t understand how to generate the json by using Ajax requests so as to get the data from the database. I want to seach into a database of thousands of people and select them according to some criteria. I cannot load all the data when loading the page.
    Can you show us an example of code that communicates with a database through Ajax/jQuery so as to generate the json? Thanks a lot, it will serve a lot of people.

  14. Rob says:

    Hello, how do you generate the json?
    Thank you

    • jiren says:

      I have generated json from rails model and hardcoded to html for demo purpose only.
      You can get json by calling api url using ajax or directly embed json object as javascript var in your html page.

  15. plenaforma says:

    Hi Jiren,
    Can you provide a complete basic example? I’ve tried myself but my example only returns one node. After filtering it only returns one attribute.

    You can find my example here:

    • jiren says:

      Your json format is incorrect, in json data after first person record you have to close “}”.
      I have missed in documentation every json element has ‘id’ field.
      i.e [{ person: {id: 1}}]
      Also template had some parent element

      Name: {{name}}
      Age: {{age}}
      Country: {{country}}

  16. Richard says:

    This is a great resource thank you. I also need to load my data from a database and seem to have success fully loaded it in. I seem to loose all the data every time I try to filter the results, I don’t suppose you could shed any light?

    • jiren says:

      Richard, Can you post javascript, html code snippet so I can check it?

      • Richard says:

        ALl has been sorted no, it was me adding in information to my JSON that didn’t need to be there.
        I don’t however seem to be able to get the search to filter using multiple links?

      • Rich says:

        Would you be able to give me a pointer on multiple link filters please. I have managed to get this working based on one data range. But am unable to get this to work on multiple ranges. I’ve pretty much duplicated all that was there with the original link filters but no joy.

        Price: 200 – 300

        Style: Print

        $(‘.filter_by_link, #clear_link_filter’).click(function(e){

        link_filter: [‘#link_filter .EVENT.change .SELECT.:input .TYPE.range’, ‘amount’],
        style_filter: [‘#style_filter .EVENT.change .SELECT.:input .TYPE.range’, ‘style_id’]

  17. Martin says:

    Hi Jiren,

    The filter functionality works great! However, is it possible that it is not supported by IE7?

    • Martin says:

      Sorry, my bad. Filtering in fact does work in IE7. There was an error in my Mustache rendering..

  18. Eric Owsley says:

    I am using ASP JSON to generate the object from an SQL source. The resulting object does not contain a top-level entity.
    var products = [
    {“ProdID”:1,”ProdName”:”816 661 120″,”Accent”:”Hammered”,”Finish”:”Gold”,”Length”:6.45},
    {“ProdID”:2,”ProdName”:”816 661 130″,”Accent”:”Hammered”,”Finish”:”silver”,”Length”:6.25},
    {“ProdID”:3,”ProdName”:”820 654 050″,”Accent”:”Bead”,”Finish”:”Gold”,”Length”:5.25}

    How can I write the “view” statement to select a single pair of values? Using “ProdID.Accent” does not work.

    If it is possible to change the data source, I am of course open to that.


    • jiren says:

      Yes, you have to change datasource format.
      i.e [ {“product”: {“id”:1,”ProdName”:”816 661 120″,”Accent”:”Hammered”,”Finish”:”Gold”,”Length”:6.45}}]

      • Eric Owsley says:

        Thank you. I have it working very well now. One question remains. I have about 2,500 JSON records to show, each with a thumbnail image, much like in your examples. Seems to be taxing to load that many initially, although once loaded the filtering works very quickly.

        Where would I begin to paginate the results?

  19. Bdg says:


    I was developping a filter via some select box. For those who are searching how to do that with filterjs here is my solution inspired by the example with the slider element :

    HTML :



    JavaScript :

    In :
    jQuery(document).ready(function($) {

    I put :

    // TYPE
    $(“#type select”).change(function () {
    $(“#typeInput”).val($(“#type select”).val());

    And in the filter_criteria, I add :

    type: [‘#typeInput .EVENT.change .SELECT.:input’, ‘nature’]

    Finally I change a bit filter.js to have a value that disable the filter (the value “all” in my select box)

    after : base.settings.selector.forEach(function(s) { (line 139)

    I add :

    if($(s.element).filter( != “all”)

    And I close it before closing : base.settings.selector.forEach(function(s) {

    Hope it can help someone,

    Thank you for your work jiren.

    • jiren says:

      Great customization.

      • Stan Slaughter says:

        I’m trying to follow this to set up using a Select tag for filtering instead of a checkbox – can you help ?

        It looks like BDg’s post may have had its formatting messed up. His HTML did not come across at all, and his comment about what to put after “jQuery(document).ready(function($) {” has an addtional “})” in it which causes formatting errors when I try it (or is it missing the starting “$(‘#typeInput’).click(function(e){“) line ?)

        Also the line numbers are different in filter.js now too. “base.settings.selector.forEach(function(s)” is not line 139 in filter.js

      • jiren says:

        After this I had updated the filter.js code so van you send me code so I can check and let you know.

      • Stan Slaughter says:

        It’s OK – through some trial and error, I figured it out. The Select tag I assigned an ID value to and made the top default option to have a value of “all”

        Note: I’m not sure how well this site handles HTML tags – I’ll use PRE tags around my snippets

          All Locations  
          AL – Decatur 

        For the Filtering I add the initial setup for city_state_list drop down inside the “jQuery(document).ready(function ($) {” bit at the top of the filterjs.js file so it would know to re-filter when a value changed

            // Initial set up for city/state select box when page loads
            $(‘#city_state_list’).change(function (e) {

        Inside filterjs.js where the “filter_criteria:” is assgined to the “settings” variabled I added the following filter criteria for the city_state_list select box

         city_state: [‘#city_state_list .EVENT.change .SELECT.:input’, ‘CityState’]

        Note: ‘CityState’ was the name of the JSON field that was hilding the ciy/state values I wanted to filter by

        OK – that pretty much did it for filterjs.js – but I had to change filter.js so that when my drop down had a value pf ‘all’ it did not attempt to filter for ‘CityState’ – looking for those with a value of ‘all’

        So – Like Bdg I modified it so that if ‘all; was a value I just excluded city_state_list from being used to filter the data. I did this by modifing the “filter: function () {” in filter.js

        I found the line in it that started looping trhough all the filters:

          base.settings.selector.forEach(function (s) {

        and put an IF stament at the top to only include filters whose current value was not ‘all

          base.settings.selector.forEach(function (s) {
            if ($(s.element).filter( != “all”) {

        and that pretty much did it.

      • Stan Slaughter says:

        Crud – even with the PRE tag this blog commenting software stripped out the select tag – I’ll try again for the select tag – using < and > HTML Entities this time

        <select id=”city_state_list”>
        <option value=”all”>All Locations</option>
        <option value=”AL – Decatur”>AL – Decatur </option>

  20. Hello,
    congratulations for the js you have written, I would say … very useful and simple to use.
    Can I ask for your help?

    I have the following list:

    Filtra per SERVIZI


    How can I integrate it in the array?
    How can I search through the action js?

    In array I added:
    where $count is a numeric variable autoincrement, is it correct? is it necessary?
    var settings = {
    filter_criteria: {
    category: [‘#category_list input:checkbox .SELECT.:checked’, ‘service_categories.ARRAY.category_id’],
    servizio_disabili: [‘#servizio_disabili_list input:checkbox .SELECT.:checked’, ‘servizio_disabili.ARRAY.category_id’],

    But it does not work, how?

    Thank you.

  21. jiren says:

    JSON is a static format so we can’t use the any dynamic statement ‘$count’ in it, so it is not going to evaluate.
    For making auto-increment $count you have to make loop and increment it before filter.js rendering.
    var count = 0;
    for(attrs in ‘JOSN var’){
    attrs[‘count’] = count;

    or you can use jquery ‘$.each(function(){})’ for looping.

  22. ayjent says:

    Interesting script – I like its simplicity.

    Has anyone tried to use this in connection with an jquery image slider/roundabout, such as roundabout or slidesjs? If the slides are dynamically generated based on form input/search input and data is retrieved from php/mysql, this filter seems like something that could parse out slide results. The biggest question may be how to eliminate placeholders for the filtered results. Seems like a perfect combination.

  23. Richard says:

    This is a fantastic resource and am glad to have found it. But I’m having major trouble with it in ie. Not even you demo on github works correctly. It there an issue with ie?

  24. arti says:

    Hello sir
    I have problem in which i have to seperate out keys and values of a json file seperately and the json file if of multiple level depth. I have done the printing part of the json file using javascript and I am not getting how to seperate out key/value pairs. if u can help me in any way then please reply.

  25. arti says:

    “SubCat”: [
    “SubCa”: [{“Cat”:”Logic”,
    “SubCaty”: [{“Cat”:”Multiv
    “PartList”: [
    ,[“abc”,”54L121″,”M Inputs”,”PULSE,IO_LEVEL,MNTYMXDLY”]

    if this is a kind of json given to us then i have to acces from AllLib to PartList and print all key/value pairs differently.

    how should I proveed for this?

  26. arti says:

    I am able to print the complete file on browser but I couldn’t identify key/value pairs seperately.. Please help me in identifying those.

  27. This script is exactly what I’ve been looking for in a long time, and right now I’m trying to get it to work with a website to add a filter for a database with roughly 3000 records. I seem to be having problems loading all records at once though. Even when I limit the SQL select to, let’s say, 500 records, the filter reacts with a significant delay (roughly 1-2 second whenever I move a slider or change a select box). I’d love to see an example of how to fill the variable that contains all the data dynamically based on the current filter selection so I don’t have to load all data when the page loads. And while I agree that pagination defeates the purpose of a filter for smaller recordsets, it might be vital for large recordsets, because otherwise, it slows down too much.

    • jiren says:

      If you want make it dynamic then you can modify filter.js for implement before filter callback just like after filter callback. In before filter you have to initialize filter.js object again.

    • Sushil says:

      Have you got the solution (Filter+Pagination for large recordset). I am also looking for the same.

      • Daniël says:

        For pagination see this comment

  28. Toby says:

    This script is really amazing!
    But I have one question concerning a filter over multiple variables – given the json object … ‘var-a’:’1′,’var-b’:’1′,’var-c’:’0′ …

    If the box a is checked, show elements where var-a is ‘1’…
    If the box b is checked, show elements where var-b is ‘1’…
    If the box ‘All’ is checked, check boxes a,b,c and show all

    Can I do this with one filter?

    Thank you!

  29. Mike says:

    I have a similar problem: I need both AND filters and OR filters in my site. Is this possible with filter.js?

    • jiren says:

      Right now only AND filter is supported. I am going to implement OR filter.

      • Mike says:

        That’s great! Thanks a lot.

      • Toby says:

        Hi thank you for going to implement OR filter, because this would solve my problem, either. Can you imagine how long it will take to implement this feature?

        Regards, T.

  30. Hi thank you for sharing such useful thing and I was looking to develop the same. Now I have decided to use filter.js for my search result filter. Thank you once again.

    While going through the article above I found some spelling mistakes or I don’t know if you have mentioned it purposely or what like appaling and Apis (appealing and API’s)

    I was looking for your mail but didn’t find any so commenting here, you can remove the comment if you want.

    Thank you,

  31. Daniël Tulp says:

    Jiren, thanks for this script. I was creating my own multiple slider and checkbox filter, but you already did it!

    3 questions:
    – pagination using this plugin: should be possible. Perhaps you can integrate it.

    – how do I call addmarkers from the jquery template view?

    – how can I use a searchbox with autocompleet to filter the data?

    Hope you can help!

    • jiren says:

      – For pagination you can implement after filter callback to render pagination links.(refer: Github: filterjs.js in example ‘filter_callbacks’)
      – You can add markers before returning the view(refer: filterjs_map.js view function)
      – For searching data you have to implement own search component.

      • Daniël Tulp says:

        Jiren, could you send me a quote to add a textfield option to filter.js? I suggest this one: or
        the code would stay part of the open sourced project and can be used by others, with no license change
        I have now used my companies e-mail address in the contact info of this comment (I’ll be on vacation the coming two weeks, but will respond afterwards)

        for the pagination, if others want it:
        use the above link to smFilteredPagination and change the hideshow function in filter.js to:
        hideShow: function (id_arr) {
        var id_str = “#” + this.settings.root + ‘_’;
        $(this.parentNode + ” > *[data-fjs]”).addClass(“filtered”);

        id_arr.forEach(function (id) {
        $(id_str + id).removeClass(“filtered”);

        to your css

        $(function(){ // document ready
        pagination = new $.smFilteredPagination($(“#projects”), {
        to your own page

        and add
        pagination: function(){
        to the filter.js callback function

  32. This is exactly what I’ve been looking for – great work.
    How would I go about setting the initial state at inclusion for all items and then individual filter selections refine the data set presented?

    • jiren says:

      You have to write json web service or include json data in your html page to include items and you can just follow the instruction given on github or this blog to add configuration.

  33. Maik M says:

    Hi. I will use the nonprofits from your site. Where can i find a download link with code from the nonprofits ?!

  34. Chris K. says:

    Thank you for this project and writeup. I’m an advanced beginner here, and have been able to work through your examples, but am getting stuck when trying to apply to my project.

    I’m running into issues when I try to use the following json:

    If I put each into an anonymous “object” fire it is seems to work.

    Is it must to have each object housed in an anonymous object?
    Something like: “fires”: [{“fire”: {“id”: 1, “type”:”house”, “damage”:”none”}}]

  35. Abhishek says:

    Hello Jiren or anyone who’s willing to help. The script is amazing, I’m having some trouble in filtering the data. I have used only checkboxes still errors are popping up. it’s just a small mistake which I’m unable to find. The problem might be in settings tab maybe. Please look at the code n help me out.

    The main html file –>

    The filterjs.js file –>

  36. How do i add a button to each object for example (Add to Cart)

  37. jiren, thanks for your quick is a link below
    I am trying to add an (Add to cart) button with a quantity text box under each item..)..
    thanks for providing a great sample//

    • jiren says:

      services.js : In view function add elements for text box and button.
      You are using old filter.js. you can get newest version from github and integrate view template like jquery template, this will make your template design task easy.

      • Jiren, I tried you filter example, it works fine on Firefox, but it doesn’t work on Internet Explorer. it produces an error on filter.js line 303 .(object doesnt support this property or method)..
        Am i missing anything?

    • jiren says:

      Use latest version of filter.js. You have used older version, in older version you can face IE issues.
      Also can you send me error so I can look into this.

  38. Abhishek says:

    Hi, We have option to add checkboxes, sliders etc. I wish to add combobox too. Can u tell me how to do it?

    2. I also wish to add a calender so that when the user clicks on that date all the items of that date are shown.

    A small push and rest I’ll manage myself. Just show the right direction,

    • jiren says:

      For combobox add same filter criteria with change event like other elements.
      For calendar set onselect event and call filtering manually or set hidden field and trigger change event like slider.

  39. Jiren, I downloaded the new version of the filter.js and it worked fine on Internet explorer, the only issue i have seen is the slider doesn’t slide correctly..and it still producing an error when you do search and filtering. thanks for fixing the error..
    Webpage error details

    User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C)
    Timestamp: Mon, 22 Oct 2012 18:52:39 UTC

    Message: ‘console’ is undefined
    Line: 125
    Char: 9
    Code: 0

    • jiren says:

      “console.log” is not supported in IE. This error is coming from callback. Remove the “logger” callback from the “filter_callbacks”. In example I have write callback for just showing how to implement callback after filter.

  40. Harsha says:

    Thank you for the plugin.

    I am trying to integrate this and here is my problem.

    I would like to filter based on the link clicked, for example if I am clicking on a link (Age :30-40) it should apply filter for Age – I got this part working till here.

    I have another link (country : NL) when I click this I would like to show the results with Age: 30-40 and Country : NL

    I can only get one filter to be applied through link. Please help me on implementing this.

    I am using the code form here

    and modified it to the code here

  41. Daniël says:


    having problems in IE8 also so I used your updated script.
    I found a problem with your execCallBacks function, v returned null (don’t know why) so I changed it to:
    execCallBacks: function (result) {
    var base = this;
    if (!base.settings.callbacks) return;

    filtered_objects = [];
    $.each(base.dataModel, function (i, v) {
    if (v != null) {
    if (result.indexOf(v[base.settings.root].id) != -1) {

    and the filtering works again
    It seems I haven’t broken any functionality, so perhaps this can help you.


    • jiren says:

      Thanks Daniël, I have updated the code for this error.

      • Hey Jiren,

        I have updated to latest code but it seems now when I have both regular filtering via radios and checkboxes enabled AND filtering via search field… only the searchfield works and regular breaks. Then if i remove the search box filtering the normal ones work. This is only in IE8.

      • actually the more testing, it seems like there just NEEDS to be a value inside of the search field for both methods to work. Even if its just an empty space/character. If there is absolutely no value in search field then the radio/checkbox filters dont work.

      • jiren says:

        Ara, If you getting error then send me error or send your filtering url so i can look into this.

  42. Maria says:

    Hi Jiren,

    Thanks for the plugin.

    I’m probably missing something here – – using the checkbox always returns only the first item. Can you please take a look?



    • jiren says:

      You have to set “id” field in every object of ‘sala_detail’ in json data.
      sala_detail :{id: 1, name:Salão Macau – Plateia ,category:Plateia ,category_id:1 ,pax:180 ,area:203 ,url:salaomacau-plateia.php}}

  43. Pingback: Antivirus Software Blog » Filter.js 1.3

  44. Ytzvan says:

    Great article, kudos!
    I’ve a question…
    Can I use this with WordPress?
    I hope you’ll help me.
    Thanks a lot.

    • jiren says:

      Yes you can use with wordpress, just you have to give input with mention format on github(

      • Amine H says:

        Hello Jiren, can you please help me integrate this to wordpress? I can play with the code, but I’d rather have you guys do it 🙂 Please contact me with a quote at:

  45. bryanwillis1 says:

    This is awesome.I’ve spent endless hours trying to get this to work, specifically with sliders. Can you update the main example on this page in full html structure? The demos are great, but they’re a little too complicated for a noob. Thanks!

  46. Dale jacobs says:

    Wondering if this is possible..
    service.start_date and service.end_date, than a filter link with data-value=today’s date, when you click it and shows all records that are past service.start_date and before service.end_date ?

    Thanks! Great plugin by the way.

    • jiren says:

      Yes you can do this, get start date value in milliseconds i.e start_date.getTime()
      Set this data-value= start_date.getTime() + ‘-‘ + end_date.getTime(). When you apply filter this work as normal integer range filter.

      • Dale Jacobs says:

        Thanks for the reply Jiren, I already have the start and end date in milliseconds but I need it to work the opposite kind of.

        Event starts 135000000 and ends 145000000, I need to click a button that has 14000000 and show any event that starts before and ends after that time stamp.

        So date-value=”below-14000000-above”

        Is that possible?

      • Dale Jacobs says:

        Something like…
        link_filter: [‘#link_filter .EVENT.change .SELECT.:input .TYPE.between’, ‘end_date-start_date’]

      • Geet Jacobs says:

        Sorry for multiple messages, but I solved this by adding some filters to your filter.js code and posting on github, maybe it will help someone else or it could be added to the code?

  47. lukemcd says:

    Thanks for the great plugin! Is it possible to restrict the search box field to certain blocks of text? Going by the included example: suppose you wanted to include only text in div.fs_head from searching typed into the input #search_box.

    • jiren says:

      For this you have to set search config like
      search: {input: ‘#searchbox’, field_selector: ‘div.fs_head’ }

      if you want multiple fields you set as comma separated.
      field_selector: ‘div.fs_head, div.fs_price’

  48. lukemcd says:

    I wanted to suggest a modification to the code. I use the suggestion by Daniël Tulp for adding pagination and it works great. His solution requires altering hideShow function in filter.js. You can change this function to allow a user to have a setting for using a class to hide items instead of the jQuery hide function. Here is the modified function:

    hideShow: function(id_arr) {
    var base = this;
    var filtered_item_class = base.settings.filtered_item_class;
    var id_str = “#” + this.settings.root + ‘_’;

    if ( filtered_item_class ) {
    $(this.parentNode + ” > *[data-fjs]”).addClass(filtered_item_class);
    else {
    $(this.parentNode + ” > *[data-fjs]”).hide();

    id_arr.forEach(function(id) {
    if ( filtered_item_class ) {
    $(id_str + id).removeClass(filtered_item_class);
    } else {
    $(id_str + id).show();

    Then in the settings the user can just add this to use a class for hiding items:
    filtered_item_class: ‘filtered’

    • can you help me with the pagination for this plugin …am not getting it

      • Daniël says:

        We’ll need more then that. I and @lukemcd explained already how to do it
        please specify what you are doing (code or better a webpage will help), what you are trying to do and what goes wrong (error messages?)

    • smith says:

      Thankx for this plugin.iam tried this but sorting and pagination both are not working at a time.can you tell me how to write this?
      After adding pagination elements is filtered and pagination are not updated.

      • jiren says:

        Can you send me code with html(just save from the browser) so I can help you.

      • smith says:

        Thanx for the reply but its not allowing that much of iam calling the pagination file like this

        pagination = new $.smFilteredPagination($(“#displayproduct”));

      • smith says:

        its some what urgent for me can you help me plss

      • smith says:

        in script for pagination

        pagination = new $.smFilteredPagination($(“#displayproduct”));

        in html

      • smith says:

        can u tell me any other plugin is there for pagination

  49. nilu says:

    hi jiren i read your article but not understand too much because i am new in .net development,i use grid view which is bind to database table and use j query slider and want to do functionality which is discuss in this article but not getting how to do all this i want to this page but how to do this please send me any complete appliction my id

    • Bryan says:

      Check out the demos, and if you download the code there are 3 complete applications already available for you to implement any way you’d like. Also, this one helped me figure it out. It uses mustache js however, but it’s pretty easy to figure out.

      • bryanwillis1 says:

        Not as though you haven’t already done enough for us all Jiren , but I agree, it would be great if you could put a more simple version in the download or if someone else could. Like the completed example of the tutorial on this page. I still haven’t been able to get that one to work. I may be wrong but in var setting I believe there is a comma missing after this line…..

        price: [‘#price_filter .EVENT.change .SELECT.:input .TYPE.range’, ‘timeleft’]

  50. Vamsi says:

    HI, Can u tell me how to load Json file step by step on scroll like yebhi,snapdeal etc,instead of loading complete json file

  51. sandeep says:

    HI Jiren! tis really an awesome work. I am keen to implement on my wordpress blog. It is a gadget site and i want a phone filter page. Could you plz explain how to integrate this into wordpress step by step as i am not a coder at all. Plz contact me at my mail id

  52. Hello,

    This looks awesome, I am trying to setup a content filtering system. and I am using expression engine as CMS. I wonder if the content needs to be hardcoded to the tags in the header (meaning the products) or is there a way to render this straightly through html and use filter.js to simple do the “filtering” part of the process. I say this because it might get tricky to get the content variables in expression engine to output products straightly to the header tag. It will be easier to control if content was already in the html to start of.

    Any ways this is a really awesome script, great work guys.

    I ll appreciate any help on what I ‘ve mentioned.



    • jiren says:

      If you do not want to render html element then you have to comment out ‘this.render();’ in _filterJS function. And one more thing you have to add ‘id’ attr to html element id i.e ‘item_1’ if your json data has root name ‘item’ and 1 is id of your record in json data and also add another attribute like ‘data-fjs’: true to html element.
      You can refer render function in js file.This will give the idea.

      • Hello Jiren,

        Thats very kind of your part, to be honest I am having a bit of trouble getting that working out, would you mind doing a minimal example (js/html) to show more precisely what you mean, I ll really appreciate that.

    • jiren says:

      Can you send me your html saved using browser, so I can look into that and suggest solution.

      • manuqc says:

        Hello Jiren,

        thanks for the reply, I do apologize for the delay. I’ve been tinkering around at different ways to make this work, and ultimately thought of using timeline.js with filter.js to filter entries.

        Timeline.js ( uses json data to populate events, and I will like to filter the entries based on the data provided. Although I am not really sure how to get this working fine. I ve seen that filter.js uses javascript vars, and timeline.js uses json data. I am wondering if there is a way to make filter.js to work with pure json data?

        this is a sample code I have in timeline.js

        “timeline”: {
        “headline”: “test”,
        “type”: “default”,
        “text”: “test”,
        “startDate”: “2009,11”,
        “date”: [
        “startDate”: “2013,3”,
        “headline”: “test”,
        “tag”: “test”,
        “text”: “”,
        “asset”: {
        “media”: “test”,
        “credit”: “Manuel”,
        “caption”: ”

        ​this is a test!

        “startDate”: “2012,11”,
        “headline”: “test – v002”,
        “tag”: “lighting”,
        “text”: “”,
        “asset”: {
        “media”: “test”,
        “credit”: “test”,
        “caption”: ”

        Lorem Ipsum is simply dummy text of the printing and typesetting industry.

        “startDate”: “2012,10”,
        “headline”: “test v003”,
        “tag”: “texturing”,
        “text”: “”,
        “asset”: {
        “media”: “test”,
        “credit”: “test”,
        “caption”: ”

        Lorem Ipsum is simply dummy text of the printing and typesetting industry.


        I will like to know if that kind of data can be used to popular content for filter.js…

        Thanks for your time
        and thanks again for this awesome plugin!



      • jiren says:

        filter.js is using json data but with the root element i.e
        [ {city: {id: 1}}, {city: {id: 2}} // city is root of record
        So your json data is correct but without root, if you want to use the below mention format then you have to modify filter.js code.

      • Geet Jacobs says:

        Hello Jiren,

        I am mainly curious why the plugin was built to use root. “filter.js is using json data but with the root element i.e [ {city: {id: 1}}, {city: {id: 2}} // city is root of record”

        When I goto validate the below json it errors. I love this plugin but always need to convert my json data to work with it, can you point me in the right direction to edit the filter.js so I can use valid json code? – json validator
        var people = [{person: {name: ‘Jiren’, age:26, country: ‘India’, country_id: 1,
        states : [{ state : ‘MH’, state_id : 3 },
        {state : ‘HN’, state_id : 4}] } },
        {person: {name: ‘Joe’, age:25, country: ‘USA’, country_id: 2,
        states : [{ state : ‘MH’, state_id : 3 },
        {state : ‘HN’, state_id : 4}] } }


      • jiren says:

        Hi Jacob
        I am going to change the code for working with both with root and without root.
        If you want to change you have to remove all “settings.root” statements and in “render” function you have to generate uniquely identify id. Currently it is generating using root
        i.e ‘person_1’, ‘person_2’ //here “person” is root.

        I have used root because in rails(active model) json serialization it used root by default now rails 3 supports json data with and without root.

      • manuqc says:

        Hello Jiren,

        Thanks for the update. Good to know there is a way to make it work! I’ll await to see your modified version of filter.js to use with/without root element. Thanks for doing this!
        I m really looking forward!



        Ps: I answer after this post because, I didnt see the “reply” available on your last post.

  53. bryanwillis1 says:

    Hey can anyone explain how the AND/OR filtering works? After looking at this, it doesn’t really make sense to me… With AND filtering shouldn’t the results show ONLY items that have BOTH or ALL of the attributes selected. So for example, if I click “Family” AND “Food and Drinks”, I would think that the ONLY results that would return are those that have BOTH family AND food and drinks attributes.

    Also, this is probably a bad question, but when using multiple range inputs when are you suppose to use $(‘#foo_filter’).trigger(‘change’); and when to use fJS.filter();? The example with the range filters is pretty complex and it’s hard to differentiate what you’re suppose to use (at least for a non-JS pro).

    • jiren says:

      AND filter is not working right now, I am going to fix this.
      For your second question.
      i.e filter criteria for range is
      [‘#price_filter .EVENT.change .SELECT.:input .TYPE.range’, ‘amount’]
      Filter.js bind change event on #price_filter for filtering, this will internally fire fJS.filter() on change event , if you want to fire filter manually you can use fJS.filter(). Here fJS is filter.js object.

  54. Pingback: filtering using checkbox in android video

  55. khushal says:

    I am using ASP.NET JSON to generate the object from an SQL source. The resulting object does not contain a top-level entity.
    var products = [

    How can I write the “view” statement to select a single pair of values? Using “ProdID.Accent” does not work.

    If it is possible to change the data source, And How to Change the Data Source??

  56. khushal says:

    Hi ..!! Jiren….!!
    i want to make it dynamic…but i dnt knw how to do..plz help me..coz my project is on deadline..
    i want to load products on pageload..
    if i write above thing in function than script is not working..plz help….
    waiting for your reply…

  57. Richard says:

    Great tool!! It’s also cool you share this great tool here 🙂
    I’ve 2 questions. (sorry I’m a java noob)
    In the example on github 1) Is it possible to give a product (or place) more then one category?

    I tried to change this in the json part
    and added another category, but jsfilter select only one.
    2) the results are shown in 3 columns now. Is it possible to make this two or one column?

  58. rg443 says:

    Reblogged this on rg443blog and commented:
    filter.js – Client side search filtering using JSON and jQuery

  59. Geet Jacobs says:

    I actually have the same question as @khushal

    I am trying to edit the code so I don’t need a sub-object, any idea how to work this out?

    Removing the “person” field.
    var people = [{id: 1, name: ‘Jiren’, age:26, country: ‘India’, country_id: 1,
    states : [{ state : ‘MH’, state_id : 3 }, {state : ‘HN’, state_id : 4}] },
    {id: 2, name: ‘Joe’, age:25, country: ‘USA’, country_id: 2,
    states : [{ state : ‘MH’, state_id : 3 }, {state : ‘HN’, state_id : 4}] }

  60. Thanga pandiyan M D says:

    Hai jiren,
    Firstly thank you for creating simple and powerful filter plugin. And I am having doubt in filter option. My issue is, when I loading page with multiple check-boxes unchecked it has to show datas only checked write? I achieved unchecked through my database status. Can we achieve this condition while is page is loading?? I am using mustache template rendering

    Please reply asap

    Thanks in advance,

    • jiren says:

      I din’t get it. Your want to show all the datas on page load or wan’t to show filtered data according to checkbox selection?

      • Thanga pandiyan M D says:

        Thank you for reply,
        I want to show filtered data according to checkbox’s selections on page load
        my code is,

        var fJS;
        jQuery(document).ready(function($) {
        fJS = filterInit();

        function filterInit(){

        var mustache_template = $(“#mustache_template”).html();

        var mustacheView = function(service){
        service.short_title = service.title.length < 15 ? service.title : service.title.substring(0,15);
        return Mustache.to_html(mustache_template, service);

        var filter_callbacks = {
        logger: function(result){


        var settings = {
        filter_criteria: {
        level: ['#level_list input:checkbox .SELECT.:checked', 'level.level_categories.ARRAY.level'],
        amount: ['#price_list input:checkbox .SELECT.:checked .TYPE.range', 'amount.amount_categories.ARRAY.amount']
        and_filter_on: true, //If any filter selection is zero then select none. For 'OR' filter set 'false'
        callbacks: filter_callbacks, //Filter callback execute in filter init and each filtering event.

        return FilterJS(services, "#leagues", mustacheView, settings);

      • jiren says:

        After calling ‘filterInit()’ call filter manually using ‘fJS.filter()’.
        fJS = filterInit();

    • Thanga pandiyan M D says:

      Thanks jiren,
      It works 🙂 ❤

  61. Glenn says:

    It’s a shame you don’t have a donate button! I’d without a doubt donate to this outstanding blog! I suppose for now i’ll settle
    for book-marking and adding your RSS feed to my Google account.
    I look forward to fresh updates and will talk about this blog with my Facebook group.

    Talk soon!

  62. sureshbvn says:


    First of all a great a piece of work from you. i have some roadblocks while using this. can you help me regarding that
    1)i have 5 filters and all are checkboxes.
    2) my json objects are very large. it contains more than 50 attributes. so i am using another json for each json called “criteria_json” which will have only these 5 values to be filtered for each json object . so i am going to filter based on my criteria file.
    3) once the filtering is done you are directly rendering the json data to the html page. instead of that i need the list of json objects which are filtered. in my case i am doing filtering based on criteria file. so if i use your filter directly criteria_json will be directly rendered in the html page.
    4) but i need to show the orginal json data in the page.
    5) please help me in getting the json data instead of rendering directly in the html page

    • jiren says:

      You can use only required fields to filter and display in json, otherwise you have to implement in view. In this function you have to find out related json object on other json and render that json.

  63. smith says:

    How can i write a pagination in filter.js.i have 256 products in a page i want to display a pagination.can any body explain me how to write a pagination.

  64. smith says:

    can anybody tell me how to write a pagination

  65. smith says:

    i added that plugin but its not working.can you tell me where i have to write that funcion

  66. smith says:

    i added that smFilteredPagination.Pagination is working correctly and products also filtered but sorting is not working.can you tell how to write both.

    Example: there are 100 products it splits in to 10 pages at that time its working correctly after filtering only 1 product will come at that time that 1 product will be stored in 10th page.remaining all the pages are empty this is my problem.can you tell me how to rectify this?

  67. smith says:

    Thanx for the reply but its not allowing that much of iam calling the pagination file like this

    pagination = new $.smFilteredPagination($(“#displayproduct”));

  68. lukemcd says:

    Hi Jiren. I have a case where I want to use filter.js in multiple instances on a single page. The issue I run into is the script is hiding all the results in every instance after the first one. Do you have recommendations for running multiple instances of filter.js?

    • jiren says:

      For each filter instance use different html container name, it’s batter use id then class
      fjs1 = FilterJS(services, “#service_list_1”, view, options);
      fjs2 = FilterJS(services, “#service_list_2”, view, options);

      Or multiple instance not working because of something else then send me detail how you are using.(some code snippet)

      • lukemcd says:

        Thanks Jiren, that’s great.

        FYI, I have an implementation of filter.js combined with jQRangeSlider and it’s looking pretty sweet!

  69. iefimoff says:

    Today I simplified your amazing example.
    Unfortunately it a little bit did not work perfectly in my case, and I cannot understand why.
    If I typing in search field the search result is empty, but after touching the price slider, this search field works correctly.



    Thanks in advance,
    WBR, Ivan

    • jiren says:

      Before filter init you have to set the value for price filter which is hidden field. When slider change the price it will update the hidden field value.

      i.e $(‘#price_filter’).val(‘0-500’); //before filter init.

      slide: function(event, ui) {
      $(“#price_range_label”).html(‘$’ + ui.values[ 0 ] + ‘ – $’ + ui.values[ 1 ] );
      $(‘#price_filter’).val(ui.values[0] + ‘-‘ + ui.values[1]).trigger(‘change’); // Hidden field value change.

  70. Mario says:

    if (property_count == 1){
    this.getRecord = function(i, d){ return d[this.root][i]; }
    Uncaught TypeError: Cannot read property ‘0’ of undefined
    this.getRecord = function(i, d){ return d[i]; }
    this.root = ‘fjs’;

    Hi Guys,

    I am trying to get your script working but I am getting this error in filter.js, Can you point where is my mistake?

    here is my JSON format:

    and here is the .js –

    Any directions?


  71. Bane says:

    Hi guys,
    I have a problem with search: {input: ‘#searchbox’ },
    Whenever i type in the input field it gives me an error:
    Uncaught TypeError: Cannot read property ‘length’ of undefined filter.js:246

    This is liine 246 ->
    var e_id = ‘#’ + this.root + ‘_’, i = 0, l = ids.length;

    • jiren says:

      Can you send me code snippet of your js code, so I can check.

    • jiren says:

      In your code filter criteria(in options) is compulsory.
      filter_criteria: {
      category: [‘#category_list input:checkbox’, ‘service_categories.ARRAY.category_id’]

    • jiren says:

      Filter Criteria

      var settings = {
      filter_criteria: {
      category: [‘#category_list input:checkbox’, ‘service_categories.ARRAY.category_id’] //Sample
      search: {input: ‘#searchbox’ },
      and_filter_on: false,

  72. Bane says:

    I added filter criteria but not sure i did it correctly because i get the error :
    uncaught TypeError: Cannot read property ‘tagName’ of undefined

    This is the edited js:
    This is the html:

    Thank you.

  73. Mario says:


    When searching in the input text field , i get the correct number of results with filter callbacks but only if the number of results is 1 the with result is displayed. If there are more than one results nothing is displayed except the number of results.

    Thanks for your help.

  74. Stephen says:

    I am trying to generate the JSON array dynamically using php:

    $row[‘ItemName’], ‘id’ => $row[‘ItemID’],’title’ => $row[‘ItemName’], ‘amount’ => $row[‘ItemPrice’]);
    echo json_encode(array(‘services’=>$services));
    The output does not seem to be in the correct format, what am i doing wrong? Is this the correct way to get the JSON dynamically?

  75. Stephen says:

    $row[‘ItemName’], ‘id’ => $row[‘ItemID’],’title’ => $row[‘ItemName’], ‘amount’ => $row[‘ItemPrice’]);
    echo json_encode(array(‘services’=>$services));

  76. hardin81 says:

    Hi jren!
    Thank you for this fantasic script!
    I’m right now using it for a developing project. I have a question though…

    Lets say you want to filter objects based of an array of dates contains in the objects available dates

    Date from: 2013-10-19
    Date to: 2013-10-21
    //Dates between array calculated: [2013-10-19, 2013-10-20]

    Check this array if all the dates is find in the objects available dates. If it does show object


    var services =
    “avaiable_dates”:[2013-10-2, 2013-10-3, 2013-10-4]
    “avaiable_dates”:[2013-10-24, 2013-10-25, 2013-10-26]
    “avaiable_dates”:[2013-10-18, 2013-10-19, 2013-10-20]


    id: 1 = false (hide)
    id: 2 = false (hide)
    id: 3 = true (show)

    Do you know a good way for filter.js to handle this?

    Best regards


  77. job says:

    hi Jiren, i have a problems to access element jsonData,
    to element array [itinerary] =>linkWebVoHRef or [itinerary] =>linkWebVoValue

    “priceSinceInResults”: “5.030 20ac”,
    “cruiseTitle”: “Leyendas del Mediterráneo 2013”,
    “tourImageLink”: {
    “imgSrc”: “/media/images/excursionesPeq.jpg”,
    “aHref”: “/cruceros/mediterraneo/leyendas-del-mediterraneo/valencia/itinerario-2013.html”,
    “aTitle”: “Excursiones Leyendas del Mediterráneo”
    “itinerary”: [
    “linkWebVoHRef”: “/destinos/espana/valencia.html”,
    “linkWebVoValue”: “Valencia”
    “linkWebVoHRef”: “/destinos/espana/malaga.html”,
    “linkWebVoValue”: “Málaga”
    “linkWebVoHRef”: “/destinos/italia/cagliari.html”,
    “linkWebVoValue”: “Cagliari”
    “linkWebVoHRef”: “/destinos/italia/civitavecchia-y-roma.html”,
    “linkWebVoValue”: “Roma (Civitavecchia)”
    “linkWebVoHRef”: “/destinos/francia/ajaccio.html”,
    “linkWebVoValue”: “Ajaccio”
    “linkWebVoHRef”: “/destinos/espana/palma-de-mallorca.html”,
    “linkWebVoValue”: “Palma de Mallorca”
    “linkWebVoHRef”: “/destinos/espana/valencia.html”,
    “linkWebVoValue”: “Valencia”
    “shipImageLink”: {
    “aHref”: “/barco/empress/camarotes.html”
    “yearItinerary”: [
    “value”: [
    “departures”: [
    “textValue”: “septiembre”
    “departures”: [
    “textValue”: “octubre”
    “departures”: [
    “textValue”: “noviembre”
    “key”: 2013
    “shipCode”: “EP”,
    “cruiseLength”: “7”


  78. hardin81 says:

    Short question 🙂
    Is it possible to run multiple text search inputs?

    searchbox1 [____________________]
    searchbox2 [____________________]
    searchbox3 [____________________]


    var settings = {
    search: {input1: ‘#searchbox1’,
    input2: ‘#searchbox2’,
    input3: ‘#searchbox3’

    • hardin81 says:

      This will make it possible to search mutliple words in an object..
      If the description somewhere contains “word1”, “word2” and “word3”.

      • jiren says:

        For this you have to customise ‘bindEvents’ and ‘search’ function. In bindEvents function you have to iterate search input and bind keyup event or you can provide same css class to all search input and bind event without iterating. While in search function you have to iterate for each searchbox and get the value and give search result for the next iteration.
        Filter.js is not searching in json data but it will search rendered html.

      • hardin81 says:

        Thank you very much Jiren!
        It works like charm! 🙂

  79. Daniël Tulp says:


    I have a problem with Perhaps you could take a look at my question at stackexchange:

    basically the problem is with the pins overlapping, a solution would be to use clusters, but I cannot get it to work

  80. Jim O'Keefe says:

    Jiren – can you post examples using drop downs? I’m trying to use the solution proposed by Stan Slaughter and BDg. I’ve got it working when I choose individual values. I’m stuck when I try to modify the filter.js file so that selecting “all” removes that category of filtering. In their comments:

    base.settings.selector.forEach(function (s) {
    if ($(s.element).filter( != “all”) {

    but “base.settings.selector…” doesn’t exist in the current filter.js file. How do I modify the filter.js file to accomplish this?

    • jiren says:

      In github stream example have selectbox. Also in that example code for selecting all. For this you have to ignore all value input and do manually call filtering.

  81. Pete Deane says:

    How can I add a thumbnail image to each filterable item? I’m not entirely sure.

  82. Chris Johnson says:

    Hi Jiren, thanks for this great bit of coding. One question, the example file stream.html is pulling the data from top_movies_data.js, and I can’t get it to pull from top_movies_data.json. In fact, if I remove the reference to the js file (<script src="top_movies_data.js"), the json file won't load at all. What am I missing? I want to reference a json doc to supply the data. Thanks in advance, -Chris

    • jiren says:

      In example I have used for initial data load. You have to give your json file path. In my example it is in data folder.

      • Chris Johnson says:

        Turns out I just had to add “var Movies = ” before the opening [ of the data in top_movies_data.json! Anyway, thanks for your quick response. I’ll send you a link to the site I’m building when it’s done, it’s a product finder that would have been impossible to build (for me anyway) without filter.js

  83. Pingback: 9 Useful jQuery Plugins For Reorganising And Filtering | Graphic & Web Design Inspiration + Resources

  84. Denis says:

    i selling a solution for pagination results from filter if anyone interested mail me at :

  85. Deepak Kushwaha says:

    Hi All, i used this library and found it awesome thanks for sharing. However, i have a case when my Json is an array of objects it doesn’t works. Any pointer will be helpful. Below is the sample of JSON i get.
    var _data = [object, object, object, object] on expanding tree in console window it shows
    0: Object
    builder: “A”
    idsite_data: 2
    image_name: “A.jpg”
    price: 12953
    size: 1582
    unit: “Unit 1”
    1: Object
    builder: “B”
    idsite_data: 3
    image_name: “A.jpg”
    price: 12953
    size: 1582
    unit: “Unit 1”

    my filter criteria is :
    builder: [‘#builder_list input:checkbox .SELECT.:checked’, ‘builder’]

    //Call to filter
    FilterJS(_data, “#projectsData”, view, settings);

    Thanks in Advance!!

  86. jim says:

    Hi, your script is great.
    I need your help. I try to use it with mysql database. I have a table with the following fileds. Id, title, price. With this table it WORKS EXCELLENT. But when I change the name of the primary key (ID to villa_id), it doesn’t work. I can’t find the code to change it.
    I’m using the example SIMPLE_FILTER.html (filter.js, simple_filter.js)

    • jiren says:

      I have added option for ‘id_field’. Check of my github repo, also I have updated simple_filter example for this kind of use case.

    • jim says:

      Hi again,
      I would also like to ask how can I add the “count results” in SIMPLE_FILTER.html. So user can know how many records he will see. (at stream.html you call “total_movies”)
      Thanks for your time!!!!

      • jiren says:

        There are callbacks like after_filter, after_add so you can update result count using callbacks. Ref:

      • jim says:

        function filterInit() {
        var template = Mustache.compile($.trim($(“#template”).html()));

        var filter_callbacks = {
        after_init: function(record_ids){
        //Call after init of filter.
        after_filter: function(result){
        before_add: function(data){
        //Process data before adding to filter while streaming.
        after_add: function(data){
        //Call after adding data to filter.

        var view = function(service){
        return template(service);

        var settings = {
        filter_criteria: {
        price: [‘#price_filter .TYPE.range’, ‘start_price’],
        stars: [‘#rating_filter .TYPE.range’, ‘persons’],
        pool: [‘#pool :checkbox’, ‘pool’],
        beach: [‘#beach :checkbox’, ‘beach’]
        //search: {input: ‘#search_box’ },
        //and_filter_on: true,

        return FilterJS(services, “#service_list”, view, settings);
        This is the code at simple_filter.js. I also add the following code at simple_filter.html.

        But nothing happens. I don’t use the proggress-bar. Is that problem?


      • Deepak kushwaha says:

        Jiren is correct, below is the exact code you need to place to print count.
        var filter_callbacks = {
        after_filter: function(result){
        $(‘#result_count’).text(‘Found : ‘ + result.length);

      • Deepak kushwaha says:

        Jiren is correct, below is the exact code you need to place to print count.
        var filter_callbacks = {
        after_filter: function(result){
        $(‘#result_count’).text(‘Found : ‘ + result.length);

      • jim says:

        Thanks Deepak Kushwaha, but it doesn’t work. I use the simple_filter.html + simple_filter.js. I test it to the prototype example, but nothing.

        var fJS;
        jQuery(document).ready(function($) {

        min: 0,
        max: 500,
        values:[0, 500],
        step: 5,
        slide: function(event, ui) {
        $(“#price_range_label”).html(‘$’ + ui.values[ 0 ] + ‘ – $’ + ui.values[ 1 ] );
        $(‘#price_filter’).val(ui.values[0] + ‘-‘ + ui.values[1]).trigger(‘change’);

        $(‘#status :checkbox’).prop(‘checked’, true);

        fJS = filterInit();

        function filterInit() {

        var template = Mustache.compile($.trim($(“#template”).html()));

        var view = function(service){
        return template(service);

        var filter_callbacks = {
        after_filter: function(result){
        $(‘#result_count’).text(‘Found : ‘ + result.length);

        var settings = {
        filter_criteria: {
        amount: [‘#price_filter .TYPE.range’, ‘amount’],
        status: [‘#status :checkbox’, ‘status’]
        search: {input: ‘#search_box’ },
        and_filter_on: true,

        return FilterJS(services, “#service_list”, view, settings);


        (span id=”result_count”> 2 span>)

      • Deepak kushwaha says:

        Hi Jim,
        I can see that you have not called callback function anywhere in settings use below snippet where i have added “callbacks: filter_callbacks”:
        var settings = {
        filter_criteria: {
        amount: [‘#price_filter .TYPE.range’, ‘amount’],
        status: [‘#status :checkbox’, ‘status’]
        search: {input: ‘#search_box’ },
        and_filter_on: true,
        callbacks: filter_callbacks

        //Hope it works for you.

      • jim says:

        Thank you very much Deepak. It works perfect.

  87. I like the valuable info you provide on your articles.
    I will bookmark your weblog and check again here frequently.
    I’m quite certain I will learn many new stuff proper right
    here! Good luck for the next!

  88. Bruce Arthur says:


    We need your solution if possible. We are using Filter.js in one of our application. In our application, there is profile page. The profile page must have reviews, profile default image and etc. The problem is we send the data thru json encoding and we are unable to get all the data. When using For each, we are not getting all the values.


    We can get the user name but we are unable to get the user id of it. Can you please give his some hints how to get the user id.

  89. abhishek Goray says:

    hi Jiren,

    Can this plugin be used with Backbone views….

    As I have a use case where we are using backbone view render our search results.

    • jiren says:

      I haven’t try with backbone, but you can define view function in that you can render view using backbone and return it.

  90. jsNoob says:

    I’m having a hard time trying to load an external JSON file without directly adding it as a file in the HTML(but using jQuery $.getJSON). Can you please help? I’m using the stream.html example.

    Thank you.

    • jiren says:

      No need to user $.getJSON to get data, you can just define “data_url” in filter.js options. filter.js wil fetch data and render it.

      • jsNoob says:

        Thank you for getting back to me so quickly. I appreciate your help.

        I can see that working for one page, but I’m using this same code to set up filtering for 3 other pages with 3 different JSON feeds. Is there an more code efficient way of doing this?

  91. Hi!
    This is what I was looking for! It´s a great tool. But I have a “problem”: I need to use it in tablets.
    I´m testing it on an iPad and the range slider is not working very well. I cannot “slide it”. I have to tap on it in order to active it, and the tap again in order to move it.

    Is there a way to fix this? I would like the slider to work like the ones that you can find in query mobile.

  92. Anita says:

    First of all thanks a lot for this code.. Filter is working for me but when I am trying pagination its not working.

    I tried incorporating changes suggested by Daniel.. if i use that hideShow funtion then filter also stops working. Where I must be going wrong?

  93. Jigar Oza says:

    Hello Good to user ..
    but i have one question is that how can i pass JSON reponse from ajax function in that..

    can you please give me some suggestion.

    Thank you.

  94. Does anyone know if the code is now working with both with root and without root JSON? If not, can anyone recommend a tool to add a root element into a JSON extract?

    • Bhaswati says:

      Yes, you can actually take “Object” as root element and write your view if you are not getting your json with root element.

      • Not sure how, could you give me an example please?

      • Bhaswati says:

        Suppose your json is coming as
        var people = [{name: ‘Tom’, age:26, country: ‘India’, country_id: 1 },
        {name: ‘Harry’, age:26, country: ‘India’, country_id: 1 }]
        you can write your view as
        var view=function(Object){
        detail=””+””+ Object.age+”;
        return detail;

        //detail should be according to how you want to display your view.
        Hope this helps..

  95. ray says:

    I wanted know if it was possible for me to beable to use your script in wordpress. I wanted use it for filtering wordpress posts

  96. Bhaswati says:

    Hi Can anyone please suggest how to include a range filter in filter criteria.I am not getting a single value rather getting a range from backend(ex: $500-600$ for salary range).how do i do client side filtering.

  97. Bhaswati says:

    I have been getting this error “ids is undefined ” in filter.js:lineno-280. for unchecking the last filter checkbox.can anyone please suggest

  98. bzzbzz says:

    Thanks for this script.
    I try to make a td table with my values.
    I used simple_filter.html:


    How and where can i add ,, tag, out of script?


    thank you.

  99. bzzbzz says:

    i add the id container in the table, the render work but not the filter.

  100. seo Google says:

    Hello there, just became aware of your blog through Google, and found
    that it’s truly informative. I am gonna watch out for brussels.
    I’ll appreciate if you continue this in future. Lots of people will be benefited from your writing.

  101. Jigar Oza says:

    I am using this Js but it is possible in this Javascript to put two search box for different-different value,

    • jiren says:

      Right now this is not possible. For this you have to customise search functionality.

      • Jigar Oza says:

        ok… but in this search box filter all value from JSON so it is possible that searchbox working for only choosen value..?

  102. jiren says:

    It is searching in html elements not in json. You can set particular html elements using search options
    i.e search: {input: ‘#search_box’ , search_in: ‘.price, .desc’},

    • Jigar Oza says:

      thank for replay but i still not get my proper result coz actually i want that from searchbox filtering for only name not for all the information if i give me any example like so its grate for me.

      Thank You.

      • jiren says:

        i.e in example folder filterjs.js add options for search. Here .fs_head is a “name” element in example.
        var options = {
        filter_criteria: {
        category: [‘#category_list input:checkbox’, ‘service_categories.ARRAY.category_id’],
        search: {input: ‘#search_box’, search_in: ‘.fs_head’ },

  103. Jigar Oza says:

    Still its not Working For me… i can not undestand that how to pass value in search: {input: ‘#search_box’, search_in: ‘.fs_head’ },

  104. Jigar Oza says:

    thank you for your hel now its working for me… but i have one problem is that i have radio button for Male and Female on page load i want data where Gender=”male” but after click on Female i can not get any data so is there any solution for that?

    Thanks in advance

  105. Jigar Oza says:

    can i load data for particular Checked Radio button value ….

  106. Anu says:

    I need a dynamically building search with some of its fields are combobox and others are text fields..can you pls tell me how to create its corresponding json for loading the dynamic form in extjs4

  107. Pingback: Search, sort, filter to plain html lists and tables through javascript | Gyankosh – Inspire !! Fun !! Innovate !!

  108. Todd says:

    Excellent blog and plugins!
    I am using your filter.js plugin on my new site, which is linked below, however it doesnt seem to work on safari… I have a feeling it may be clashing with another script but not sure how to fix it. it works fine on everything else. Any ideas?

  109. Konstantin says:

    Hi jiren,
    Do you have any ideas how to implement dynamic (lazy) creation of result blocks when scrolling down the page and removing them after filtering? See examples and

  110. Victor Cintron says:

    Is it possible to start with a clear google map and then populate it with the filters?

    • jiren says:

      Yes you can do it in after filter callback. Right now in example after filter callback changes only places markup points so in place of markup points change code you can init google map and mark points .

  111. can you filter by dates?

    • jiren says:

      Yes you can write custom filter type. In example there is time range custom filter same way we can implement date custom filter.

  112. Oh Come on says:
    These examples links lead to
    which just shows an empty template page.
    The github example works (and looks nice)

  113. Reblogged this on Play!ng with Scala and commented:
    I am planning to integrate it with Play framework.

  114. Daniël Tulp says:

    I want to stop getting updates from this blog because of spam. Please remove my e-mail address.

  115. Pingback: Fix Messagelistfilter.js Errors - Windows XP, Vista, 7 & 8

  116. Pingback: Fix Externalfilters.js Errors - Windows XP, Vista, 7 & 8

  117. Pingback: Fix Queryfilter.js Errors - Windows XP, Vista, 7 & 8

  118. binod says:

    How would you define arrary of states in view function?

  119. Seb says:

    I can’t achieve filtering with a multiple select.
    Works fine with a simple one with :
    FJS.addCriteria({field: ‘myField’, ele: ‘#myselect’, selector: ‘select’ })

    Is this a limitation or am I missing something?


  120. Yassine says:

    Thank you for this Wonderfull Plugin.

    But how can i get the current item cliqued after the callback function??

    Thank you

  121. Yousuf says:

    Great tutorial! However, my project stumbled on “Cannot read property ‘replace’ of undefined” line 76 in filter.js(link at the top of this page). Any ideas? Has anyone else noticed this?

  122. LAURA says:

    I’m a newbie and need to create a search criteria function much like yours that primarily uses checkboxes. I’m having issues since I’ve never worked much with js before. Using in vs2013. Do you have video tutorials/other references I can use? My project revolves around filtering search results by checking/unchecking boxes, no postbacks, all clientside. Uses RDF database.

  123. Fausto says:

    Thanks for such effective tool !!
    One question:
    If my data is as follow,
    var records = [
    {“name”: “Somebody”,
    “props”: {“p1”: “v1”, “p2”: “v2”}
    “id”: 1


    How can I set the filter criteria field for p1 or p2?
    Would it be…?
    {field: ‘props[“p1”]’, ele: ‘#p1’}
    or otherwise?
    Thanks in advance, Fausto

  124. Fausto says:

    It’s me again. Sorry, I just found the answer to my previous question / comment in your GitHub page (copied below just in case):

    For nested field selection. In below object to select filter on name field option value would be, for city

    Json object:
    detail: { name: ‘Jiren’, address: {city: ‘Pune’} }

  125. Jon says:
    On the states drop down list the filter only works when I have state selected. if it is on “All States” then it looks for those states=”. How can I get the default of that drop down to tell the filter to look at everyone? I can do it with checkboxes, or if it was a range, but it isn’t either!

  126. Francois says:

    Hi. Thank you for this great tool. How can I change this tool to filter flowers by month and color?

    Basically I want the slider to slide between January and December so then you can set it to only show flowers that’s available between February and June for example?

    Sorry, I’m not sure how to do this.

  127. Fausto says:

    Two questions about cdn
    1. Is there any cdn hosting filter.js?
    2. Could you submit filter.js to cdnjs Library Repository? (
    Thanks again, Fausto

  128. julian says:

    HI Jiren

    Thank you very much for your example Filter.js

    I have a question . well as the total of the movies that are in your last upgrade “250” .

    How can I know how many of them are from “Crime “, ” Drama” , “Adventure ”

    Example : when you load the page see ” movies ( 250 ) ” ok . Now as few of the ” 250 ” is are “crime (XX) ” , ” Drama (XX) , without filtering .

    Also as I can you order in ascending and descending by “rating” When i press button .

    I have about 1200 records but since I can put pagination?

    Greetings Julian

  129. Fausto says:

    How to define the field in the filter criteria if the json object in the array is as follow
    detail: { name: ‘Jiren’, ‘Org Unit’: ‘Head Office’ }

    I tried as follow, but got an error (Uncaught TypeError: undefined is not a function)
    {field: ‘detail[“Org Unit”]’, ele: ‘#filter_criteria input:checkbox’}

    Thanks in advance, Fausto

  130. yogesh says:

    How to multiple search_box work?

    st = StreamTable(‘#stream_table’,
    view: view,
    per_page: 10,
    data_url: ‘data/movies.json’,
    stream_after: 0.5,
    auto_sorting: true,
    fetch_data_limit: 100,
    callbacks: callbacks,
    pagination: {span: 5, next_text: ‘Next →’, prev_text: ‘← Previous’},
    search_box: ‘#st_actor’, fields: [‘actor’],
    search_box: ‘#st_search’, fields: [‘year’, ‘name’]
    , data);

    • jiren says:

      Only one searchbox is working currently. You need to customize search event binding and search function to achieve this.

      Thanks Jiren – sent from mobile


      • julian says:

        hi Jiren

        How i can know the register number of “crime”, “adventure”, etc of your example filter.js
        i know the total register is
        callbacks: {
        afterFilter: function(result){

  131. Aratm says:

    Hi Juren.

    What must be my criteria to work with a multi-select?

  132. Nestor says:

    I work with .NET, and I’m quite new to handling json data. After doing some research, I wasn’t able to find a simple way to translate your views into

    Obvoiusly in .net means other stuff thatn json. So it won’t work as it is.

    Got any idea of how to rewrite this views simple as they are so that It’s easy to use them in .net webforms?


  133. Alexei says:

    Jiren, Hi! Can you help me. filtr.js – best work. The problem is how can i do five checkbox group on this page

    I need:
    1) When visitor come to the page all chexkboxes are not checked, but the list of events is viewed all.
    2) When visitor check the box -> filtering by parametr1
    3) When visitor check other box -> filtering by parametre2
    So events filtering by parametr1 and parametr2 and etc.

    Thank you for answer!

  134. Edwin says:

    Great work Jiren, is there a way to group the filter result according to a category or id.

  135. chran says:

    Hi i am using this plugin to apply filter on my data. i am building bootstrap panel with json objects. now i want to show star rating for every panel using jquery raty plugin. when included that code in this rating is not coming. can u please help me this regard. actually i was struck in my application development.

    for reference find the below code

    Micro-template returned by filter.js json object is :


    My Jquery is :
    number: function() {
    return $(this).attr(‘data-score’);

  136. sudarshan says:

    For me its not working Its saying templateBuilder is not defined and FilterJS is not defined when I have given correct path to it. I have added filter.js and basic.js. I have used this with opencart to test. Even after loading needed libraries in correct order why I am getting these errors? Please reply

  137. sudarshan says:

    Is there any way to ignore case sensitiveness because I added to range and it only works for either uppercase value or lowercase value. Suppose I am looking for km and i have set its value as KM then it only works for KM not for km. I am talking about dropdown selection.

  138. madhuri says:

    Hi Great JS, Just wanted some updates or fiddle if you can provide me to work with sorting, I need to apply sorting criteria please provide some fiddle to work with sorting by high to low and vice versa. Also If we can do it drop down.

  139. Hems says:

    How to use this filter concept in JSP pages, because won’t work in JSP.

  140. moriya hisashi says:

    Thank you for a great script.
    There is one hope. or you will not be able to use the gmap3.js in map.js?
    Customizing the map is can be easily, I believe or not the various functions is attached. Or change the marker for each category, such as marker cluster.
    Certainly please examine.
    Nice to meet you.

  141. shandles says:

    Hi – love this script, we use it every day! However, we recently ran into an issue where this line fails (ver 1.5.1) :

    return FilterJS(services, "#service_list", view, settings);

    since the code thinks that the variable services is not yet defined. I’ve tried to declare services as variable in the calling PHP as well as earlier in the JS function, but both fail to work like they used to. Is there an easy fix to this problem – it used to work till about 3-6 months ago.

    Would be great if we didn’t have to revisit the entire implementation to resolve this issue.

    Thanks again!

  142. Dirk Fischer says:

    great solution!
    how can I add an Input textbox as filter criteria to have one searchbox and a second textbox as additionnal filter criteria? I tried the following but with no success:

    FJS.addCriteria({field: ‘genre’, ele: ‘#genres’, event: ‘change’, selector: ‘:input’ })


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s