I have a form_tag that submits a user’s search remotely to a Rails controller method, which returns the results in JS format.
How can I automatically submit this form:
- When a user has entered in at least 2 characters
- When the user has paused for at least 1 second?
Bind a keypress handler to the input using jQuery. In the callback, start a timer using
setTimeoutto submit the form after one second and keep a hold of the timer ID thatsetTimeoutreturns to you. If you have a non-null timer ID when your keypress callback is triggered, stop the timer withclearTimeoutand set the timer ID to null; if they also have two characters at this point, then start the timer (again) and store the timer ID (again).So, you have a process in the keypress handler like this:
clearTimeout, null the timer ID, and continue.setTimeoutand store the timer ID, the function attached to the timer would submit the form.