Search code examples
javascripthtmljsptypeahead.jstwitter-typeahead

Twitter typeahead not preserving value after user selects an option


I am trying to optimize a dropdown selection bar to typeahead autocomplete using twitter's typeahead. When I implemented twitter's typeahead, I couldn't preserve the value which user selected or type it after refreshing the page. Also, when I try to submit the form I am working on, it seems like it's never recorded as a value field.

This is my code :

Substring matcher for autocomplete and suggestion

var substringMatcher = function(strs) {
          return function findMatches(q, cb) {
            var matches, substringRegex;
            matches = [];
            substrRegex = new RegExp(q, 'i');
            jQuery(function ($){
                  $.each(strs, function(i, str) {
                      if (substrRegex.test(str)) {
                          matches.push(str);
                      }
                  });
                  cb(matches);
              });
          };
    };

Typeahead

 var Array = [];
        jQuery(function ($) {
                $(document).ready(function(){
                    $('#project').typeahead({
                                hint: true,
                                highlight: true,
                                minLength: 1
                            },
                            {
                                name: 'Projects',
                                source: substringMatcher(Array)
                            });
                });

            });

html

<c:forEach items="${Form.projectList}" var="val">
   <script type="text/javascript">
        var Projects = "${val.project}";
        Array.push(Projects);
   </script>
</c:forEach>

<div id="the-basics">
   <input id = "project" class="typeahead" type="text" placeholder="Projects">
</div>

Can anyone give me any suggestions on how I should figure out this problem ?


Solution

  • … when I try to submit the form I am working on, it seems like it's never recorded as a value field.

    Your input element is missing a name attribute, which is required for the input’s value to be sent when the form is submitted. Try using this HTML:

    <input id="project" name="project" class="typeahead" type="text" placeholder="Projects">
    

    I am not sure if this will also solve the problem where the value is lost when the page refreshes, or if that requires an additional solution.