Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<script type="text/javascript"></script>
<body>
<center>
From Date:<br>
<input type="date" id="datefrom" name="datefrom" class="auto-save">
<br>
To Date:<br>
<input type="date" id="to" name="dateto" class="auto-save">
<br>
</center>
<br><br><br><br>
<button type="button" name="button" onclick="dstry()">Destroy all data</button>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha384-vk5WoKIaW/vJyUAd9n/wmopsmNhiy+L2Z+SBxGYnUkunIxVxAv/UtMOhba/xskxh" crossorigin="anonymous"></script>
<script type="text/javascript" src="savy.js"></script>
<script type="text/javascript">
$('.auto-save').savy('load',function(){
console.log("All data from savy are loaded");
});
function dstry(){
$('.auto-save').savy('destroy',function(){
console.log("All data from savy are Destroyed");
window.location.reload();
});
}
</script>
savy.js
(function($) {
$.fn.savy = function(order,fn) {
const sv = "savy-";
if (order == "load") {
$(this).each(function() {
if ($(this).is(":radio")) {
if(localStorage.getItem(sv+$(this).attr("name"))){
if (localStorage.getItem(sv+$(this).attr("name")) == this.id) {
this.checked = true;
}else{
this.checked = false
}
}
$(this).change(function() {
localStorage.setItem(sv+$(this).attr("name"), this.id);
});
}else if($(this).is(":checkbox")){
if(localStorage.getItem(sv+this.id)){
this.checked = (localStorage.getItem(sv+this.id) == "1" ? true : false);
}
$(this).change(function() {
localStorage.setItem(sv+this.id, (this.checked ? "1" : "0"));
});
}else if($(this).is("input") || $(this).is("textarea")) {
if(localStorage.getItem(sv+this.id)){
this.value = localStorage.getItem(sv+this.id);
}
$(this).keyup(function() {
localStorage.setItem(sv+this.id, this.value);
});
}else if($(this).is("select")) {
if ($(this).is("[multiple]")) {
if(localStorage.getItem(sv+this.id)){
$(this).val(localStorage.getItem(sv+this.id).split(","));
}else{
localStorage.setItem(sv+this.id, $(this).val());
}
$(this).change(function() {
localStorage.setItem(sv+this.id, $(this).val());
});
}else{
if(localStorage.getItem(sv+this.id)){
$(this).val(localStorage.getItem("savy-"+this.id));
}else{
localStorage.setItem(sv+this.id, $(this).val());
}
$(this).change(function() {
localStorage.setItem(sv+this.id, $(this).val());
});
}
}
});
if ($.isFunction(fn)){fn();}
}else if (order == "destroy") {
$(this).each(function() {
if(localStorage.getItem(sv+this.id)){
localStorage.removeItem(sv+this.id)
}
});
if ($.isFunction(fn)){fn();}
}else{
console.error("savy action not defined please use $('.classname').savy('load') to trigger savy to save all inputs")
}
};
})(jQuery);
No comments:
Post a Comment