Search code examples
jqueryruby-on-railsautocompletejquery-tokeninput

Dynamic Autocompletion in Rails, using the jQuery TokenInput Plugin


I'm using the great TokenInput plugin (http://loopj.com/jquery-tokeninput/) for rails to do some autocompletion and for a normal set of data in a model it works just wonderfully. But my problem is, that in my case I have actually 2 textboxes I want to use it on, and the suggestions for the second one should depend on the content of the first. More specifically: I need to select a football club (which I can just autocomplete out of all exisiting clubs in my database) and then the team that played. So the autocompletion for the team should only use the teams associated with the already selected club and I'm completely clueless about how or even if I can do that in rails and with this plugin (but the plugin itself shouldn't really be a hindrance). I guess my main problem here is my lack of experience with javascript, especially in combination with rails. Did anyone do something like that in his/her application and could help me?


Solution

  • Your question could have many different edge cases. Have a look at the tokenInput method 'onResult'.

    Maybe you could get the current values from the first input field(input-1) and assess the returned json for input-2 against input-1 and filter out the ones you don't want. You would obliviously have to include the needed id elements for filtering in the json array that rails creates.

    <script type="text/javascript">
            $(document).ready(function() {
                $("#input-1").tokenInput("http://railsapp.com/your/search/action");
    
                $("#input-2").tokenInput("http://railsapp.com/your/search/action", {
                    onResult: function (results) {
                        var input-1 = $("#input-1").val();
                        $.each(results, function (index, value) {
                            // some JS to keep only results which match input-1 values
                        });
    
                        return results;
                    }
                });
            });
            </script>
    

    DISCLAIMER: This is just an idea.

    Hope this helps.