Skip to content

Instantly share code, notes, and snippets.

@lyoshenka
Created February 28, 2014 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lyoshenka/9280740 to your computer and use it in GitHub Desktop.
Save lyoshenka/9280740 to your computer and use it in GitHub Desktop.
How to autosave a form field as it's being edited. This will fire the ajax request 400ms after the person stops typing.
// inspired by http://stackoverflow.com/questions/2006870/submit-form-with-delay-while-entering-data-into-input-field
/*
var timerid;
jQuery("#searchForm").keyup(function() {
var form = this;
clearTimeout(timerid);
timerid = setTimeout(function() { form.submit(); }, 500);
});
*/
$('form').on('input', 'input.autosubmit', function() {
var $this = $(this),
timer = $this.data('timer'),
delay = 400;
if (timer) {
clearTimeout(timer);
}
$this.data('timer', setTimeout(function() {
if ($this.val() !== $this.data('value')) {
$this.data('value', $this.val());
$.get('url-goes-here', { value: $this.val() }, function(data) {
if (!data.success) {
alert('Saving data failed.');
}
});
}
}, delay));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment