Setting local storage for Datepicker - javascript

I have a J query code which shows the date picker
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#datepicker" ).datepicker();
} );
</script>
</head>
<body>
<div id = "date">
<p>Date: <input type="text" id="datepicker"></p>
</div>
</body>
</html>
I have tried local storage to save the date inside the textfield, but it seems to erase on page refresh. Please help. Thanks a lot for your time.
My local storage code
<script type="text/javascript">
document.getElementById("datepicker").value = getSavedValue("datepicker"); // set the value to this input
/* Here you can add more inputs to set value. if it's saved */
//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
var id = e.id; // get the sender's id to save it .
var val = e.value; // get the value.
localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
}
//get the saved value function - return the value of "v" from localStorage.
function getSavedValue (v){
if (!localStorage.getItem(v)) {
return "";// You can change this to your defualt value.
}
return localStorage.getItem(v);
}
</script>

Check the below snippet to store and update data with localStorage
Update localStorage with the selected date when datepicker is closed, with onClose event
Set back the date from localStorage to datepicker on load of the document
Note: Snippet is throwing an error as localStorage is not accessible within the below sandbox.
var storage = {
saveDate: function (dateText, instance) {
// If not valid date take last selected value
var validDateText = dateText ? (dateText.match(/\d{2}\/\d{2}\/\d{4}/) || [instance.lastVal])[0] : "";
var data = JSON.parse(localStorage.getItem('jq-ui-datepicker') || "{}");
data[instance.id] = validDateText;
localStorage.setItem('jq-ui-datepicker', JSON.stringify(data));
instance.input.val(validDateText);
},
getDate: function () {
var data = JSON.parse(localStorage.getItem('jq-ui-datepicker') || "{}");
$(".datepicker").each(function () {
var $this = $(this),
dateText = data[$this.attr('id')];
if (dateText) {
// Set date to datepicker
$this.datepicker('setDate', dateText);
}
})
}
}
$(function () {
$(".datepicker").datepicker({
onClose: storage.saveDate
});
storage.getDate();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"
integrity="sha512-uto9mlQzrs59VwILcLiRYeLKPPbS/bT71da/OEBYEwcdNUk8jYIy+D176RYoop1Da+f9mvkYrmj5MCLZWEtQuA=="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css"
integrity="sha512-aOG0c6nPNzGk+5zjwyJaoRUgCdOrfSDhmMID2u4+OIslr0GjpLKo7Xm0Ao3xmpM4T8AmIouRkqwj1nrdVsLKEQ=="
crossorigin="anonymous" />
<div id="date">
<p>Date - 1: <input type="text" id="date1" class="datepicker"></p>
<p>Date - 2: <input type="text" id="date2" class="datepicker"></p>
</div>

Related

Creating an autocomplete function in Google script that works with a list of values from the Google Sheet

I'm trying to create an autocomplete text field, that autocompletes the country that's filled in, if the country already exists in the google sheet. At the moment my code only works, when I write all the possible countries in the 'availabletags' variable. But I want it to get the values directly from the google sheet. This is the html & script:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="ui-widget">
<label for="text">country</label>
<input id="text">
</div>
<div>
<button id="btn"> Run it! </button>
</div>
<script>
$(function() {
var availableTags = [ //should be changed to availableTags = list;
"belgium",
"france",
"greece",
"spain",
"italy",
"the netherlands"
];
$("#text").autocomplete({
source: availableTags
});
});
document.getElementById("btn").addEventListener("click", doStuff);
function doStuff() {
var ucountry = document.getElementById("text").value;
google.script.run.userClicked(ucountry);
document.getElementById("text").value = "";
};
</script>
</body>
</html>
I wrote following code in google script to retrieve the countries from the google script, and when I look at the log, the list of countries from the google sheet is indeed in the list variable.
function doGet() {
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var list = ws.getRange(1,1,ws.getRange("A1").getDataRegion().getLastRow(),1).getValues(); // contains countries
Logger.log(list);
var template = HtmlService.createTemplateFromFile("page");
template.list = list.map(function(r){return r[0]; });
var html = template.evaluate();
return html;
}
function userClicked(country){
var url = "https://docs.google.com/spreadsheets/d/1IMxZwN3swMTf9EoF_k3iRV7Zc6iwzoWzov5-qC_MSKU/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
ws.appendRow([country]);
}
I would like to have the var availableTags = list; But when I do that, the autocomplete stops working. Any help would be appreciated!
Use google.script.run with SuccessHandler
This implies the creation of an additional .gs function that will be called from clientside onload.
Sample:
Code.gs
function doGet() {
var template = HtmlService.createTemplateFromFile("page");
var html = template.evaluate();
return html;
}
function getCountry(){
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var list = ws.getRange(1,1,ws.getRange("A1").getDataRegion().getLastRow(),1).getValues(); // contains countries
list = list.map(function(r){return r[0]; });
Logger.log(list);
return list;
}
function userClicked(country){
var url = "https://docs.google.com/spreadsheets/d/1IMxZwN3swMTf9EoF_k3iRV7Zc6iwzoWzov5-qC_MSKU/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
ws.appendRow([country]);
}
page.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="ui-widget">
<label for="text">country</label>
<input id="text">
</div>
<div>
<button id="btn"> Run it! </button>
</div>
<script>
google.script.run.withSuccessHandler(tags).getCountry();
function tags(list) {
console.log(list);
var availableTags = list;
$("#text").autocomplete({
source: availableTags
});
};
document.getElementById("btn").addEventListener("click", doStuff);
function doStuff() {
var ucountry = document.getElementById("text").value;
google.script.run.userClicked(ucountry);
document.getElementById("text").value = "";
};
</script>
</body>
</html>

How do I store kendoMultiSelect selected values in an array variable?

I want to store selected values from the dropdown into an array but getting null values.
Is this a correct way to store selected values in an array?
var selecteddeliverableLists = ko.observableArray();
function loadDeliverableKeyValuePairs() {
deliverableKeyValuePairLists.removeAll();
$.get("/common/packagestatus/get/pairs", function (responseData) {
var dataArray = deliverableKeyValuePairLists();
responseData.forEach(function (o) {
dataArray.push({
Id: o.key,
Name: o.value
});
});
deliverableKeyValuePairLists.valueHasMutated();
}).done(function () {
selecteddeliverableLists = $("#deliverable__kendo__selection").kendoMultiSelect({
dataTextField: "Name",
dataValueField: "Id",
optionLabel: " -- Select All -- ",
dataSource: deliverableKeyValuePairLists(),
index: 0,
change: filterdeliverable
//onChangeDeliverableFilter
});
});
selecteddeliverableLists.valueHasMutated();
}
function filterdeliverable() {
var newval = selecteddeliverableLists.val();
console.log(newval);
}
You get the value as element_name.data("kendoMultiSelect").value();
function filterdeliverable() {
var newval = $("#deliverable__kendo__selection").data("kendoMultiSelect").value();
console.log(newval);
}
You can use the change event of the kendoMultiSelect to store the new values array when the change is made.
You can use the new array right in the change event's callback function or use it later.
See a simple example in the following snippet:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.917/styles/kendo.common.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.917/styles/kendo.rtl.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.917/styles/kendo.silver.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.917/styles/kendo.mobile.all.min.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.917/js/kendo.all.min.js"></script>
</head>
<body>
<select id="multiselect" multiple="multiple">
<option>Item1</option>
<option>Item2</option>
</select>
<button onclick="$('#output').html(values.map(function (value) {return '<li>' + value + '</li>'}))">Update</button>
<ul id="output"></ul>
<script>
var values = [];
$("#multiselect").kendoMultiSelect({
change: function(e) {
values = this.value();
}
});
</script>
</body>
</html>

Cant submit html form after use js script

I have this html site
<html>
<head>
<link rel="stylesheet" href="~/Content/index.css" />
<link rel="stylesheet" href="~/Scripts/fancyBox/source/jquery.fancybox.css" type="text/css" media="screen" />
<meta name="viewport" content="width=device-width" />
<script type="text/javascript" src="~/Scripts/prototype.js"></script>
<script type="text/javascript" src="~/Scripts/scriptaculous.js?load=effects"></script>
<script type="text/javascript" src="~/Scripts/Scale.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="~/Scripts/fancyBox/source/jquery.fancybox.pack.js"></script>
<title>Countries</title>
</head>
<body>
<div>
#foreach (var country in Model)
{
<a class="fancybox">
<div class="tooltip">
#using (Html.BeginForm("ChangeCulture", "Home", new { lang = country.Culture }))
{
<!-- onclick="zoomIn('#country.Culture')"-->
<input id="#country.Culture" class="#country.Sprite" type="image" name="submit" src="//" />
<span class="tooltiptext">#country.Country</span>
}
</div>
</a>
}
</div>
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
afterShow : function() {
this.find("form").submit();
}
});
})
</script>
</body>
</html>
The bottom line is that the flags of countries with tooltips are displayed on the screen and by pressing it is necessary to change the language of the tooltips to the language used in the country. I did this, and now I need to increase the whole screen after receiving the picture with the flag, and then the language would change. I found the fancybox scripts, but after it is inserted, the form is not sent, the selected flag appears in the center, but nothing happens after that, what could be the problem? I have not written to asp and js before
After click on the image I got an error
Uncaught TypeError: this.find is not a function
at Object.afterShow (Index:119)
at Function.trigger (jquery.fancybox.pack.js:17)
at HTMLDivElement._afterZoomIn (jquery.fancybox.pack.js:33)
at HTMLDivElement.d.complete (jquery-latest.min.js:4)
at j (jquery-latest.min.js:2)
at Object.fireWith [as resolveWith] (jquery-latest.min.js:2)
at i (jquery-latest.min.js:4)
at m.fx.tick (jquery-latest.min.js:4)
My method
public ActionResult ChangeCulture(string lang)
{
var returnUrl = this.Request.UrlReferrer?.AbsolutePath;
var cookie = this.Request.Cookies["lang"];
if (cookie != null)
{
cookie.Value = lang;
}
else
{
cookie = new HttpCookie("lang")
{
HttpOnly = false,
Value = lang,
Expires = DateTime.Now.AddYears(1)
};
}
this.Response.Cookies.Add(cookie);
return this.Redirect(returnUrl ?? "Index");
}
You should user jquery selector
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
afterShow : function() {
$(".fancybox").submit();
}
});
})
The error is located in this statement:
this.find("form").submit();
You're trying to call find() method on plain JS object inside this wrapper, where the function belongs to a jQuery object. The correct way is using jQuery object like this:
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
afterShow : function() {
// alternative: use $(this).closest("form").submit();
$(this).find("form").submit();
}
});
});
</script>
Additionally your redirection method in controller action should be like below, since Controller.Redirect requires full path or URL for redirect to another page:
public ActionResult ChangeCulture(string lang)
{
var returnUrl = this.Request.UrlReferrer?.AbsolutePath;
// cookie settings here
if (string.IsNullOrEmpty(returnUrl))
{
return this.RedirectToAction("Index");
}
return this.Redirect(returnUrl);
}
The this in this.find("form") is not $(".fancybox") here.
Try using $('.fancybox form') instead.

How do I get Date Range Picker selected date to a variable?

hi i am using data range picker for filter option. there is change with default date picker range is . here i am using a div instead of text box. so tthat i need the selected start date and end date in a variable how can i due it?. i try like this way...
$('#Date').daterangepicker();
$(document).on("click",".applyBtn",function() {
// var range = $('#Date').datarangepicker.getRange();
// var startDate = range.start;
// var endDate = range.end;
var x =$('#Date').data('daterangepicker').StartDate()
alert(x);
});
<!-- Include Required Prerequisites -->
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap/3/css/bootstrap.css" />
<!-- Include Date Range Picker -->
<script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />
<div id="Date" class="col-xs-5 col-md-4 paddingNull filterImageAlign" >here select</div>
Try this.
var startDate = $('#Date').data('daterangepicker').startDate._d;
var endDate = $('#Date').data('daterangepicker').endDate._d;
If you need to get it formatted locally
$('#Date').daterangepicker().on('apply.daterangepicker', function (e, picker) {
var startDate = picker.startDate.format('DD-MM-YYYY');
var endDate = picker.endDate.format('HH:mm');
})

Dialog Box with Input Element

I want to have a dialog window with an input. I could use the default jQuery-ui one, but I am using one that incorporate bootstrap. However, the input only appears the first time that it is opened, any subsequent times the dialog is opened, the input is missing. How would this be remedied?
Here is the HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<link rel="stylesheet" href="../bower_components/jquery-ui/themes/base/jquery.ui.all.css">
<link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="../bower_components/bootstrap3-dialog/css/bootstrap-dialog.min.css">
<link rel="stylesheet" href="../bower_components/bootstrap-datepicker/css/datepicker3.css">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h3>Hello!</h3>
<div>
<span>Enter a Zip Code: </span>
<input type="text" id="zip">
<button id="getEvents" class="btn btn-primary">Get events!</button>
</div>
<div class="datepicker"></div>
<div id="events"></div>
<button id="addItemButton">Add an item</button>
<div id="addItemDialog"><input type="text" id="newItem"></div>
<script src="../bower_components/jquery/jquery.min.js"></script>
<script src="../bower_components/jquery-ui/ui/jquery-ui.js"></script>
<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="../bower_components/bootstrap3-dialog/js/bootstrap-dialog.js"></script>
<script src="../bower_components/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
<script src="js/calendar.js"></script>
</body>
</html>
Here is the JS:
$(function () {
"use strict";
var url,
year,
month,
zip,
date,
events = [],
newItem;
$("#addItemDialog").hide();
$(".datepicker").datepicker({dateFormat: "yy-mm-dd"}).click(function(){
$("#events").empty();
date = $(".datepicker").datepicker("getDate");
//console.dir(date.toISOString().substr(0, 10));
$(events).each(function(i, event){
//console.log(event);
if(event.date.substr(0, 10) === date.toISOString().substr(0, 10)){
console.log(event.title);
$("#events").append("<h4 class='event'>" + event.title + "</h4>");
}
});
});
$("#getEvents").on("click", function () {
zip = $("#zip").val();
if(isValidUSZip(zip)){
zip = zip.substr(0, 5);
getCalendar();
}else{
BootstrapDialog.show({
message: "You must enter a valid zip code!",
buttons: [{label:"OK", action: function(dialog){dialog.close();}}],
draggable: true
});
}
});
function isValidUSZip(sZip) {
return /^[0-9]{5}(?:-[0-9]{4})?$/.test(sZip);
}
function getCalendar() {
$.ajax({
type: "GET",
url: "http://www.hebcal.com/hebcal/?v=1&cfg=json&nh=on&nx=on&year=now&month=x&ss=on&mf=on&c=on&zip=" + zip +"&m=72&s=on",
success: function (data) {
console.dir(data);
$(data.items).each(function(index, item){
//console.dir(item.date.substr(0, 10));
events.push(item);
});
}
});
}
$("#addItemButton").on("click", function(){
BootstrapDialog.show({
message: $("#newItem"),
buttons: [{
label: "Enter",
action: function(dialog){
newItem = $("#newItem").val();
events.push({date: new Date(date).toISOString(), title: newItem});
dialog.close();
}
}]
});
});
});
I took a time and make this fiddle, aparently everything is working fine:
I doubt about this line for a moment, but still uncommented is going right:
$(function () {
//"use strict";
var url,
year,
month,
zip,
date,
events = [],
newItem;
http://jsfiddle.net/r2FyC/3/

Categories