Autosave input box's to database during pause in typing?

前端 未结 3 1578
慢半拍i
慢半拍i 2021-01-30 17:43

I have a large form on my website that I want to be able to autosave to a database as the user is filling it out. Almost identical to how google drive works when typing a docume

相关标签:
3条回答
  • 2021-01-30 17:57

    I know that this question is old, but I would like to include a code that I like the most. I found it here: http://codetunnel.io/how-to-implement-autosave-in-your-web-app/

    Here is the code:

    var $status = $('#status'),
        $commentBox = $('#commentBox'),
        timeoutId;
    
    $commentBox.keypress(function () {
        $status.attr('class', 'pending').text('changes pending');
    
        // If a timer was already started, clear it.
        if (timeoutId) clearTimeout(timeoutId);
    
        // Set timer that will save comment when it fires.
        timeoutId = setTimeout(function () {
            // Make ajax call to save data.
            $status.attr('class', 'saved').text('changes saved');
        }, 750);
    });
    

    It saves after the user stops writing for more than 750 milliseconds.

    It also has a status letting the user know that the changes have been saved or not.

    0 讨论(0)
  • 2021-01-30 18:00

    Try Sisyphus.js https://github.com/simsalabim/sisyphus. It persists the form data in the browser's local storage and is robust against tabs closing, browser crashes, etc...

    0 讨论(0)
  • 2021-01-30 18:06

    Debounce the textarea change.

    Demo: jsFiddle

    Put your ajax call in the saveToDB() function. These event names('input propertychange change') will trigger on any form element change such as radio buttons, inputs, etc.

    var timeoutId;
    $('#the-textarea').on('input propertychange change', function() {
        console.log('Textarea Change');
    
        clearTimeout(timeoutId);
        timeoutId = setTimeout(function() {
            // Runs 1 second (1000 ms) after the last change    
            saveToDB();
        }, 1000);
    });
    
    function saveToDB()
    {
        console.log('Saving to the db');    
    }
    

    Here is a full demo showing you how to debounce a full form and use ajax to send the data and then return the status (Saving, Saved, etc).

    Demo full form and ajax: jsFiddle

    0 讨论(0)
提交回复
热议问题