JSFiddle - React, Tailwind, and code Playground
by gromer
HTML
<div id="exit-div"><a href="#" id="exit">Exit</a></div>
<div id="form-div">
<form id="a-form">
<p>
<label for="name">Name:</label>
<input type="text" name="name" value="Mike" class="watchable" />
</p>
<p>
<label for="phone">Phone:</label>
<input type="text" name="phone" value="8015554125" />
</p>
<p><input type="button" id="check" value="Check for Changes" /></p>
</form>
</div>
<div id="results-div">
<span>Results:</span>
<ul id="results"></ul>
</div>
<div id="output-div">
<span><a href="#" id="clear-output">Output:</a></span>
<div ></div>
</div>
CSS
form p {
margin-bottom: 10px;
}
div {
padding: 10px;
}
JavaScript
(function($) {
var settings = {
'inputs': 'input',
'triggerSelector': null
};
var methods = {
init : function(options) {
settings = $.extend(settings, options);
return this.each(function(index, element) {
var $this = $(this);
$(document).on('click', settings['triggerSelector'], displayConfirmation);
$this.find(settings['inputs']).each(function(i, elem) {
var $elem = $(elem);
$elem.data('originalValue', $elem.val());
});
});
},
getChangeCount : function() {
return getChangeCount(this);
}
};
$.fn.changeWatcher = function(method) {
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.changeWatcher' );
}
};
function displayConfirmation(e) {
e.preventDefault();
var response = confirm('There are unsaved changes on the page, are you sure you want to exit? All changes will be lost.');
if (response === true) {
log('Exiting');
}
}
function getChangeCount(container) {
var count = 0;
container.each(function(index, element) {
var $this = $(container);
$this.find(settings['inputs']).each(function(i, elem) {
var $elem = $(elem);
var originalValue = $elem.data('originalValue');
var currentValue = $elem.val();
if (originalValue !== currentValue) {
count += 1;
}
});
...