]> granicus.if.org Git - jq/commitdiff
Autocomplete manual search to first result on submit
authorDavid Tolnay <dtolnay@gmail.com>
Tue, 13 Oct 2015 17:46:49 +0000 (10:46 -0700)
committerDavid Tolnay <dtolnay@gmail.com>
Tue, 13 Oct 2015 17:48:06 +0000 (10:48 -0700)
docs/public/js/manual-search.js
docs/templates/manual.liquid

index c2b13dec18646528336a6eb26209ced761581662..eb7cff893a7cd2ecfc327d76468288c236e55d90 100644 (file)
@@ -1,4 +1,7 @@
-var section_names = function(q, cb) {
+var section_names = function(q) {
+  if (!q) {
+    return [];
+  }
   var matches = [];
   q = q.toLowerCase();
   $.each(section_map, function(k, v) {
@@ -10,23 +13,31 @@ var section_names = function(q, cb) {
     // shortest to longest
     return a.length - b.length;
   });
-  cb(matches);
+  return matches;
+}
+var section_names_cb = function(q, cb) {
+  cb(section_names(q));
 }
-var go_to_section = function(section) {
-  if (section in section_map) {
-    location.hash = '#' + section_map[section];
+var go_to_section = function() {
+  query = $('#searchbox').val();
+  results = section_names(query);
+  if (results.length == 0) {
+    return;
+  }
+  result = results[0];
+  location.hash = '#' + section_map[result];
+  if (result != query) {
+    $('#searchbox').val(result);
   }
 }
 $(function(){
   $('#searchbox').typeahead(
     {hint: false, highlight: true, minLength: 1},
-    {name: "contents", source: section_names, limit: 6}
+    {name: "contents", source: section_names_cb, limit: 6}
   ).on('typeahead:selected', function(e, data) {
-    go_to_section($(this).val());
-  });
-  $('#searchbox').change(function() {
-    go_to_section($(this).val());
+    go_to_section();
   });
+  $('#searchbox').change(go_to_section);
 });
 // add "Run" button to execute examples on jqplay.org
 $(function() {
index 59505a955cf3b93e3ff1ff8d3a577ad139ef211d..f1d7985a55c7f0767c6e21b055ca97d395da66c3 100644 (file)
@@ -16,7 +16,7 @@
               </li>
             {% endfor %}
           </ul>
-          <form class="form-group">
+          <form class="form-group" onsubmit="go_to_section(); return false;">
             <input type="text"
                   class="form-control"
                   placeholder="Search"