Save 1 second after Form Change

Debouncing form input change

by Eric

HTML

<div>
    Demo with example ajax call <a href="http://jsfiddle.net/MadLittleMods/NxQ4A/">here</a>
</div>
<br />

<form class="contact-form" method="post">
    First name: <input type="text" name="fname"><br>
    Last name: <input type="text" name="lname"><br>
    <input type="radio" name="sex" value="male">Male<br>
    <input type="radio" name="sex" value="female">Female<br>
    <input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
    <textarea id="the-textarea"></textarea><br>
    <input type="submit" value="Submit">
</form>
<div class="form-status-holder"></div>

JavaScript

var timeoutId;
$('form input, form 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');
    
    // Now show them we saved and when we did
    var d = new Date();
    $('.form-status-holder').html('Saved! Last: ' + d.toLocaleTimeString());
}