JSFiddle - React, Tailwind, and code Playground
HTML
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css">
<form id="form">
<fieldset>
<legend>Legend<span id="state" class="pull-right">Clean</span></legend>
<label>Label name</label>
<input type="text" placeholder="Type something…" />
<span class="help-block">Example block-level help text here.</span>
<label class="checkbox">
<input type="checkbox" /> Check me out
</label>
<label class="checkbox inline">
<input type="checkbox" id="inlineCheckbox1" value="option1" /> 1
</label>
<label class="checkbox inline">
<input type="checkbox" id="inlineCheckbox2" value="option2" /> 2
</label>
<label class="checkbox inline">
<input type="checkbox" id="inlineCheckbox3" value="option3" /> 3
</label>
<br />
<select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<br />
<select multiple="multiple">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</fieldset>
</form>
<div class="form-actions">
<button class="btn btn-primary" id="save">save</button>
<button class="btn" id="read">read state</button>
</div>
JavaScript
(function($){
$.fn.isDirty = function(handler) {
var el = $(this);
if(typeof el.data('isDirty') != 'undefined') {
if(typeof handler == 'boolean') {
el.data('isDirty', handler);
}
return el.data('isDirty');
}
el.data('isDirty', false);
var _isExcludedKey = function (keyCode) {
if(keyCode == 9) return true; // tab
if(keyCode == 37) return true; // arrow key left
if(keyCode == 38) return true; // arrow key up
if(keyCode == 39) return true; // arrow key right
if(keyCode == 40) return true; // arrow key down
};
el.change(function(){
el.data('isDirty', true);
handler.call(this);
});
el.keypress(function(key) {
if(!_isExcludedKey(key.keyCode)) {
el.data('isDirty', true);
handler.call(this);
}
});
handler.call(this);
};
})(jQuery);
// init
$('#form').isDirty(function() {
// callback function is optional
var state = ($('#form').isDirty()) ? 'Watch out! Dirty form!' : 'Nice and clean';
$('#state').html(state);
});
// check current form state
$('#read').on('click', function(e) {
var state = ($('#form').isDirty()) ? 'Watch out! Dirty form!' : 'Nice and clean';
$('#state').html(state);
return false;
});
// save form, and clean dirty state
$('#save').on('click', function(e) {
$('#form').isDirty(false);
$('#read').click();
return false;
});