Search code examples
jqueryautosuggestproactive

jQuery FAQ autosuggest answer below title as per StackOverflow


I want to have a support form use the content of the 'problem title' field as a trigger to add a div below with possible answers just as StackOverflow does when you submit a new question.

To clarify, I do not want the suggested answers to be presented as a 'auto-complete' option, I want them to appear below as a suggested answer.

The markup in the page might be something like:

<input type="text" value="" placeholder="Your problem in brief">
<div id="PossibleAnswers" class="hidden">
<ul>
    <li><a href="#">Possible answer 1</a></li>
    <li><a href="#">Possible answer 2</a></li>
    <li><a href="#">Possible answer 3</a></li>
</ul>
</div>

As the user starts to type the summary of their problem the div below would populate with suggested answers.


Solution

  • I managed to get something up and running, here's what I ended up with:

    var do_live_search = function() {
    
            var stopwords = new Array("a","about","an","and","are","as","at","be","by","but","can't","from","how","i","in","is","it","of","on","or","that","the","this","to","was","we","what","when","where","which","with","won't");
    
            var keywords = $("#Trigger").val().split(" ");
    
            var clean_keywords = new Array();
    
            $.each(keywords,function(i,val){
                if(($.trim(val) != "")
                    && ($.inArray(val,stopwords)==-1)
                    && ($.inArray(val,clean_keywords)==-1)
                    && (val.length > 3)
                    ){
                    clean_keywords.push(val);
                }
            });
    
            if (clean_keywords.length >= 1) {
    
                var joined_keywords = clean_keywords.join('|');
    
                $.get("/fetch/_search_support_faqs?q="+joined_keywords+"", function(mydata){
    
                    if (mydata != "") {
    
                        $.each(mydata, function(i, item) {
                            $('#MatchingFAQs ul').append(
                                $('<li>').append(
                                    $('<a>').attr('href','#FAQ_'+mydata[i].entry_id).append(mydata[i].title)
                            )); 
                        });
    
                        $('#MatchingFAQs').slideDown('slow');
                    }
    
                });
    
            }
        }
    

    This was then triggered using the 'Type Watch' plug-in for jQuery (https://github.com/dennyferra/TypeWatch):

    var typewatch_options = {
            callback:do_live_search,
            wait:500,
            highlight:true,
            captureLength:3
        }
    
        // Watch for key up events in the search field
        $("input#Trigger").typeWatch(typewatch_options);