Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to autosave HTML5 search input through javascript / without refresh

Question:
Is there any way to trigger Webkit's autosave functionality from javascript? If not through a dedicated API, is there at least a way to accomplish the same functionality by manipulating cookies?

Background:
I really like the new "search" input type in HTML5 and want to give my Webkit-enabled users the benefit of easily recalling their past searches without the overhead of storing all those searches in my database (using the autosave functionality).

The problem I'm hitting is that the search terms seem to only get saved if the search input is encapsulated in a form and that form executes a standard POST on submit. Since my search input is being used to filter results that are already present it doesn't make much logical sense to completely reload the page, so I'm using AJAX to repopulate the results. The interface is all clean and consistent if I return false in my AJAX function, but this obviously doesn't trigger the form POST [by design] so the browser (at least Chrome) doesn't save the search term. Returning true refreshes the entire page, destroying my AJAX-injected content and the entire point of the filter, but the search term is saved.

$('#filter-form').submit(function(e) {
      var term = $('#filter').val();
      $.ajax({
        async: true,
        type: 'POST',
        url: '/Home/GetResults',
        data: {
          filter: term
        },
        success: function(returnData) {
          $('#result-list').html(returnData);
        }
      });
      return false;
    }
<form id="filter-form" name="filter-form" action="#">
  <input type="search" name="filter" id="filter" results="5" autosave="EluminitePreviousFilters" />
</form>
<div id="result-list"></div>
like image 514
Eluminite Avatar asked Jan 29 '13 01:01

Eluminite


People also ask

How do I AutoSave Javascript?

Add class="Autosave" to every form in your page that you wish to be saved automatically in the background. Then insert <script type="text/javascript" src="autosave. js"></script> at the bottom of your HTML page. This script automatically hides any submit buttons for those forms when it's activated.


1 Answers

There is a trick that uses a hidden iframe connected to the form:

<iframe id="hidden-frame" name="hidden-frame" style="display:none" src="about:blank"></iframe>

<form target="hidden-frame" method="post" action="about:blank">
  <input type="search" name="filter" id="filter" results="5" />
  <button type="submit">Submit</button>
</form>

If your form submit handler returns true, form will be submitted (but users won't notice), and the browser will save the entered value in the autocomplete list.

I've created an example on JSBin: http://jsbin.com/farelufaku/edit?html,output

like image 54
Michał Dudak Avatar answered Oct 12 '22 00:10

Michał Dudak