I need to set the time value in time picker which I'm putting in another text box.
like if I put 10:30 PM in my text box then on button click in another text box which have wicked timepicker in it
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<link rel="stylesheet" href="stylesheets/wickedpicker.css">
<script src="src/wickedpicker.js"></script>
<input type="text" class="input" id="time"/><br>
<input type="text" class="input" id="time1"/><br>
<input type="button" value="Show" id="btn"/>
in jquery I tried this-
$("#time").wickedpicker();
$("#btn").click(function(){
var val=$("#time1").val();
$("#time").wickedpicker("setTime",val);
$("#time1").wickedpicker("setTime",val);
alert("selected time is " + val);
});
I did the same with date picker and it worked so I thought it would work with this but its no use even alert is not working, its saying value undefine.
Below code include the modification of wicked picker js in order to change and update picker value.
/**
* wickedpicker v0.4.1 - A simple jQuery timepicker.
* Copyright (c) 2015-2016 Eric Gagnon - http://github.com/wickedRidge/wickedpicker
* License: MIT
*
* Modified to allow changing the time.
* Example:
* var options = {now: "12:35"};
* var myPicker = $('.timepicker').wickedpicker(options);
*
* myPicker.wickedpicker('setTime', 0, "14:00"); // 0 is the index of the timepicker. Use 0 if only one
*/
!function($,window,document){"use strict";"function"!=typeof String.prototype.endsWith&&(String.prototype.endsWith=function(e){return e.length>0&&this.substring(this.length-e.length,this.length)===e});var isMobile=function(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)},today=new Date,pluginName="wickedpicker",defaults={now:today.getHours()+":"+today.getMinutes(),twentyFour:!1,upArrow:"wickedpicker__controls__control-up",downArrow:"wickedpicker__controls__control-down",close:"wickedpicker__close",hoverState:"hover-state",title:"Timepicker",showSeconds:!1,timeSeparator:" : ",secondsInterval:1,minutesInterval:1,beforeShow:null,afterShow:null,show:null,clearable:!1,closeOnClickOutside:!0,onClickOutside:function(){}};function Wickedpicker(e,t){this.element=$(e),this.options=$.extend({},defaults,t),this.element.addClass("hasWickedpicker"),this.element.attr("onkeypress","return false;"),this.element.attr("aria-showingpicker","false"),this.createPicker(),this.timepicker=$(".wickedpicker"),this.up=$("."+this.options.upArrow.split(/\s+/).join(".")),this.down=$("."+this.options.downArrow.split(/\s+/).join(".")),this.separator=$(".wickedpicker__controls__control--separator"),this.hoursElem=$(".wickedpicker__controls__control--hours"),this.minutesElem=$(".wickedpicker__controls__control--minutes"),this.secondsElem=$(".wickedpicker__controls__control--seconds"),this.meridiemElem=$(".wickedpicker__controls__control--meridiem"),this.close=$("."+this.options.close.split(/\s+/).join("."));var i=this.timeArrayFromString(this.options.now);this.options.now=new Date(today.getFullYear(),today.getMonth(),today.getDate(),i[0],i[1],i[2]),this.selectedHour=this.parseHours(this.options.now.getHours()),this.selectedMin=this.parseSecMin(this.options.now.getMinutes()),this.selectedSec=this.parseSecMin(this.options.now.getSeconds()),this.selectedMeridiem=this.parseMeridiem(this.options.now.getHours()),this.setHoverState(),this.attach(e),this.setText(e)}$.extend(Wickedpicker.prototype,{showPicker:function(e){"function"==typeof this.options.beforeShow&&this.options.beforeShow(e,this.timepicker);var t=$(e).offset();if($(e).attr({"aria-showingpicker":"true",tabindex:-1}),this.setText(e),this.showHideMeridiemControl(),this.getText(e)!==this.getTime()){var i=this.getText(e),s=/\s\w\w$/.test(i)?i.substr(-2,2):null,o=i.replace(/\s\w\w$/,"").split(this.options.timeSeparator),n={};n.hours=o[0],n.minutes=o[1],this.options.showSeconds?(n.seconds=o[2],n.meridiem=s):n.meridiem=s,this.setTime(n)}this.timepicker.css({"z-index":this.element.css("z-index")+1,position:"absolute",left:t.left,top:t.top+$(e)[0].offsetHeight}).show(),"function"==typeof this.options.show&&this.options.show(e,this.timepicker),this.handleTimeAdjustments(e)},hideTimepicker:function(e){var t;this.timepicker.hide(),"function"==typeof this.options.afterShow&&this.options.afterShow(e,this.timepicker),function(){var e=$.Deferred();return $('[aria-showingpicker="true"]').attr("aria-showingpicker","false"),e.promise()}().then((t=0,void setTimeout(function(){$('[aria-showingpicker="false"]').attr("tabindex",t)},400)))},createPicker:function(){if(0===$(".wickedpicker").length){var e='<div class="wickedpicker"><p class="wickedpicker__title">'+this.options.title+'<span class="wickedpicker__close"></span></p><ul class="wickedpicker__controls"><li class="wickedpicker__controls__control"><span class="'+this.options.upArrow+'"></span><span class="wickedpicker__controls__control--hours" tabindex="-1">00</span><span class="'+this.options.downArrow+'"></span></li><li class="wickedpicker__controls__control--separator"><span class="wickedpicker__controls__control--separator-inner">:</span></li><li class="wickedpicker__controls__control"><span class="'+this.options.upArrow+'"></span><span class="wickedpicker__controls__control--minutes" tabindex="-1">00</span><span class="'+this.options.downArrow+'"></span></li>';this.options.showSeconds&&(e+='<li class="wickedpicker__controls__control--separator"><span class="wickedpicker__controls__control--separator-inner">:</span></li><li class="wickedpicker__controls__control"><span class="'+this.options.upArrow+'"></span><span class="wickedpicker__controls__control--seconds" tabindex="-1">00</span><span class="'+this.options.downArrow+'"></span> </li>'),e+='<li class="wickedpicker__controls__control"><span class="'+this.options.upArrow+'"></span><span class="wickedpicker__controls__control--meridiem" tabindex="-1">AM</span><span class="'+this.options.downArrow+'"></span></li></ul></div>',$("body").append(e),this.attachKeyboardEvents()}},showHideMeridiemControl:function(){!1===this.options.twentyFour?$(this.meridiemElem).parent().show():$(this.meridiemElem).parent().hide()},showHideSecondsControl:function(){this.options.showSeconds?$(this.secondsElem).parent().show():$(this.secondsElem).parent().hide()},attach:function(e){var t=this;this.options.clearable&&t.makePickerInputClearable(e),$(e).attr("tabindex",0),$(e).on("click focus",function(e){$(t.timepicker).is(":hidden")&&(t.showPicker($(this)),window.lastTimePickerControl=$(this),$(t.hoursElem).focus())});var i=function(e){if($(t.timepicker).is(":visible")){if($(e.target).is(t.close))t.hideTimepicker(window.lastTimePickerControl);else if($(e.target).closest(t.timepicker).length||$(e.target).closest($(".hasWickedpicker")).length)e.stopPropagation();else{if("function"==typeof t.options.onClickOutside?t.options.onClickOutside():console.warn("Type of onClickOutside must be a function"),!t.options.closeOnClickOutside)return;t.hideTimepicker(window.lastTimePickerControl)}window.lastTimePickerControl=null}};$(document).off("click",i).on("click",i)},attachKeyboardEvents:function(){$(document).on("keydown",$.proxy(function(e){switch(e.keyCode){case 9:"hasWickedpicker"!==e.target.className&&$(this.close).trigger("click");break;case 27:$(this.close).trigger("click");break;case 37:e.target.className!==this.hoursElem[0].className?$(e.target).parent().prevAll("li").not(this.separator.selector).first().children()[1].focus():$(e.target).parent().siblings(":last").children()[1].focus();break;case 39:e.target.className!==this.meridiemElem[0].className?$(e.target).parent().nextAll("li").not(this.separator.selector).first().children()[1].focus():$(e.target).parent().siblings(":first").children()[1].focus();break;case 38:$(":focus").prev().trigger("click");break;case 40:$(":focus").next().trigger("click")}},this))},setTime:function(e){this.setHours(e.hours),this.setMinutes(e.minutes),this.setMeridiem(e.meridiem),this.options.showSeconds&&this.setSeconds(e.seconds)},getTime:function(){return[this.formatTime(this.getHours(),this.getMinutes(),this.getMeridiem(),this.getSeconds())]},setHours:function(e){var t=new Date;t.setHours(e);var i=this.parseHours(t.getHours());this.hoursElem.text(i),this.selectedHour=i},getHours:function(){var e=new Date;return e.setHours(this.hoursElem.text()),e.getHours()},parseHours:function(e){return!1===this.options.twentyFour?(e+11)%12+1:e<10?"0"+e:e},setMinutes:function(e){var t=new Date;t.setMinutes(e);var i=t.getMinutes(),s=this.parseSecMin(i);this.minutesElem.text(s),this.selectedMin=s},getMinutes:function(){var e=new Date;return e.setMinutes(this.minutesElem.text()),e.getMinutes()},parseSecMin:function(e){return(e<10?"0":"")+e},setMeridiem:function(e){var t="";void 0===e?t="PM"===this.getMeridiem()?"AM":"PM":t=e;this.meridiemElem.text(t),this.selectedMeridiem=t},getMeridiem:function(){return this.meridiemElem.text()},setSeconds:function(e){var t=new Date;t.setSeconds(e);var i=t.getSeconds(),s=this.parseSecMin(i);this.secondsElem.text(s),this.selectedSec=s},getSeconds:function(){var e=new Date;return e.setSeconds(this.secondsElem.text()),e.getSeconds()},parseMeridiem:function(e){return e>11?"PM":"AM"},handleTimeAdjustments:function(e){var t=0;$(this.up).add(this.down).off("mousedown click touchstart").on("mousedown click",{Wickedpicker:this,input:e},function(e){if(1!=e.which)return!1;var i=this.className.indexOf("up")>-1?"+":"-",s=e.data;"mousedown"==e.type?t=setInterval($.proxy(function(e){e.Wickedpicker.changeValue(i,e.input,this)},this,{Wickedpicker:s.Wickedpicker,input:s.input}),200):s.Wickedpicker.changeValue(i,s.input,this)}).bind("mouseup touchend",function(){clearInterval(t)})},changeValue:function(operator,input,clicked){var target="+"===operator?clicked.nextSibling:clicked.previousSibling,targetClass=$(target).attr("class");targetClass.endsWith("hours")?this.setHours(eval(this.getHours()+operator+1)):targetClass.endsWith("minutes")?this.setMinutes(eval(this.getMinutes()+operator+this.options.minutesInterval)):targetClass.endsWith("seconds")?this.setSeconds(eval(this.getSeconds()+operator+this.options.secondsInterval)):this.setMeridiem(),this.setText(input)},setText:function(e){$(e).val(this.formatTime(this.selectedHour,this.selectedMin,this.selectedMeridiem,this.selectedSec)).change()},getText:function(e){return $(e).val()},formatTime:function(e,t,i,s){var o=e+this.options.timeSeparator+t;return this.options.twentyFour&&(o=e+this.options.timeSeparator+t),this.options.showSeconds&&(o+=this.options.timeSeparator+s),!1===this.options.twentyFour&&(o+=" "+i),o},setHoverState:function(){var e=this;isMobile()||$(this.up).add(this.down).add(this.close).hover(function(){$(this).toggleClass(e.options.hoverState)})},makePickerInputClearable:function(e){$(e).wrap('<div class="clearable-picker"></div>').after("<span data-clear-picker>×</span>"),$("[data-clear-picker]").on("click",function(e){$(this).siblings(".hasWickedpicker").val("")})},timeArrayFromString:function(e){if(e.length){var t=e.split(":");return t[2]=t.length<3?"00":t[2],t}return!1},_time:function(){var e=$(this.element).val();return""===e?this.formatTime(this.selectedHour,this.selectedMin,this.selectedMeridiem,this.selectedSec):e},_setTime:function(e){this.options.now=e;var t=this.timeArrayFromString(this.options.now);this.options.now=new Date(today.getFullYear(),today.getMonth(),today.getDate(),t[0],t[1],t[2]),this.selectedHour=this.parseHours(this.options.now.getHours()),this.selectedMin=this.parseSecMin(this.options.now.getMinutes()),this.selectedSec=this.parseSecMin(this.options.now.getSeconds()),this.selectedMeridiem=this.parseMeridiem(this.options.now.getHours()),this.setText(this.element);var i=$(this.element).val();return""===i?this.formatTime(this.selectedHour,this.selectedMin,this.selectedMeridiem,this.selectedSec):i},_hide:function(){this.hideTimepicker(this.element)}}),$.fn[pluginName]=function(e,t,i){return $.isFunction(Wickedpicker.prototype["_"+e])?$(this).hasClass("hasWickedpicker")?"setTime"===e?void 0!==t?$.data($(this)[t],"plugin_"+pluginName)._setTime(i):$.data($(this)[0],"plugin_"+pluginName)._setTime(i):void 0!==t?$.data($(this)[t],"plugin_"+pluginName)["_"+e]():$.data($(this)[0],"plugin_"+pluginName)["_"+e]():void 0:this.each(function(){$.data(this,"plugin_"+pluginName)||$.data(this,"plugin_"+pluginName,new Wickedpicker(this,e))})}}(jQuery,window,document);
$(document).ready(function() {
var timepicker = $("#time").wickedpicker();
$("#btn").click(function(){
var time = timepicker.wickedpicker('time');
time = time.replace(' : ', ' ');
var h = time.split(' ')[0];
var m = time.split(' ')[1];
var ampm = time.split(' ')[2];
if (ampm == 'PM') {
h = parseInt(h) + 12;
}
var options2 = {
now: h+':'+m,
};
var time1 = $("#time1").wickedpicker(options2);
time1.wickedpicker('setTime',0, h+':'+m)
});
});
<link href="https://www.jqueryscript.net/demo/Minimal-jQuery-Timer-Picker-Plugin-Wickedpicker/stylesheets/wickedpicker.css" rel="stylesheet"/>
<input type="text" class="input" id="time"/><br>
<input type="text" class="input" id="time1"/><br>
<input type="button" value="Show" id="btn"/><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
1) Use wickedpicker('time') to get time value instead.
2) Convert time in 24 hours format before assigning the time value.
$('#time1').wickedpicker();
$('button').on('click', function() {
// get time form time1
var t = ($('#time1').wickedpicker('time'));
// convert to 24 hours format
t = t.replace(' : ', ' ');
var h = t.split(' ')[0];
var m = t.split(' ')[1];
var ampm = t.split(' ')[2];
if (ampm == 'PM') {
h = parseInt(h) + 12;
}
// set time to time2
$('#time2').wickedpicker({now: h+':'+m});
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/wickedpicker#0.4.3/dist/wickedpicker.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/wickedpicker#0.4.3/dist/wickedpicker.min.js"></script>
Time 1: <input type="text" class="time" id="time1"><br>
Time 2: <input type="text" class="time" id="time2"><br>
<button>Click Me</button>
I used the following code to set the time (timeTokens is array consisting of hour and minute):
var setTimePicker = function (timeTokens) {
$('.wickedpicker__controls__control--hours').text(timeTokens[0]);
$('.wickedpicker__controls__control--minutes').text(timeTokens[1]);
wickedpicker.data('plugin_wickedpicker').selectedHour = timeTokens[0];
wickedpicker.data('plugin_wickedpicker').selectedMin = timeTokens[1];
}
I'm trying to make an alert to user when choose a date. For example, when user choose 2018-09-13, then the alert will show message "7 days later will be 2018-09-20". But instead, the alert message shows 2018-09-137.
<input type="date" name = "date" id = "date" onchange="javascript:var chooseDate=(this.value)+7; alert('7 days later will be '+chooseDate);" >
How should I add days into the date ?? please help, thank you.
this.value will return the date as string using the format YYYY-MM-DD, so if you "add" 7, it will be YYYY-MM-DD7. What you could do is create a new Date object, and then add the days you want, like this:
var chooseDate=new Date(this.value);
chooseDate.setDate(chooseDate.getDate()+7);
alert('7 days later will be '+chooseDate);
This will give you the complete date, though, which is something you probably don't want, so you would have to get the values you actually need, like this:
var chooseDate=new Date(this.value);
chooseDate.setDate(chooseDate.getUTCDate()+7);
var futureDate = chooseDate.getFullYear()+'-'+('0'+(chooseDate.getMonth()+1)).slice(-2)+'-'+('0'+(chooseDate.getDate())).slice(-2);
alert('7 days later will be '+chooseDate);
Here you have a working example:
<input type="date" name = "date" id = "date" onchange="var chooseDate=new Date(this.value);chooseDate.setDate(chooseDate.getUTCDate()+7);var futureDate=chooseDate.getFullYear()+'-'+('0'+(chooseDate.getMonth()+1)).slice(-2)+'-'+('0'+(chooseDate.getDate())).slice(-2);alert('7 days later will be '+futureDate);" >
How about this in :
addDays = function(input_date, days) {
var date = new Date(input_date);
date.setDate(date.getDate() + days);
return date;
}
You then call do addDays(this.value, 7) in onchange().
And, please reference on getDate() and setDate().
You are working with string instead of a date object:
function lPad(val) {
return ((10 > val ? '0' : '') + val);
}
function add(input, unit, value) {
var cur = input.value;
var byValue = Number(value);
if (!/^\d{4}\-\d{2}\-\d{2}$/.test(cur) || !/day|month|year/.test(unit) || isNaN(byValue)) {
console.warn('invalid parameters!');
return false;
}
var dt = new Date(cur.replace(/\-/g, '/'));
if (!dt || isNaN(dt)) {
console.warn('invalid date!');
return false;
}
if ('day' === unit) {
dt.setDate(dt.getDate() + byValue);
} else if ('month' === unit) {
dt.setMonth(dt.getMonth() + byValue);
} else {
dt.setFullYear(dt.getFullYear() + byValue);
}
input.value = [dt.getFullYear(), lPad(1 + dt.getMonth()), lPad(dt.getDate())].join('-');
console.log(cur, value, unit, '=', input.value);
return true;
}
<input type="date" onchange="add(this,'day','+7');" title="+7 days" />
<input type="date" onchange="add(this,'month','-1');" title="-1 month" />
<input type="date" onchange="add(this,'year','+2');" title="+2 year" />
try this one ...
<input type="date" name = "date" id = "date" onchange="ggrr(this)" >
<script>
function ggrr(input){
var dateString = input.value;
var myDate = new Date(dateString);
var d = new Date(Date.parse(myDate));
var y = d.getFullYear();
var da = d.getDate() + 7;
var m = d.getMonth();
console.log(y+':'+m+':'+da);
}
</script>
I have two date fields. Field 2 works fine. Clicking anywhere on the input type date for second fields opens the calendar. But the same is not working for first date field. When I click on the calendar icon for date field it opens the calendar but I want that calendar should pop up when I click anywhere on the date field for field 1 as well.
Why does it works for the second field but not for the first field.
Also the default date is not getting set to todays date.
http://jsfiddle.net/KJ4e5/3/
HTML
<body>
<div id="doc">
<table>
<tr>
<td>
<input name="date1" id="date1" type="date" data-role="datebox" data-options='{"mode": "calbox","dateFieldOrder":["d","m","y"], "useNewStyle":true,"overrideDateFormat": "%d/%m/%Y", "afterToday":true}' />
</td>
<td>
<input name="date2" id="date2" type="date" data-role="datebox" data-options='{"mode": "calbox","dateFieldOrder":["d","m","y"], "useNewStyle":true,"overrideDateFormat": "%d/%m/%Y", "afterToday":true}'/>
</td>
</tr>
</table>
</div></body>
//JS
$( document ).on( "pageinit", "#doc", function() {
var defaultPickerValue = new Date();
var today = defaultPickerValue.getDate() + "/" + (defaultPickerValue.getMonth()+1) + "/" + defaultPickerValue.getFullYear();
$('#date1').val(today);
$('#date2').val(today);
$('#date1').on('change', function() {
if ( $('#date2')) {
$('#date2').val($('#date1').val());
var temp = new Date();
var start = $('#date1').datebox('getTheDate');
var diff = parseInt((start - temp) / ( 1000 * 60 * 60 * 24 ));
diffstrt = (diff * -1)-1;
$("#date2").datebox("option", {
"minDays": diffstrt
});
}
});
});
I can't explain why the 2 boxes act differently, but if you explicitly assign the useFocus option to the boxes, they will both work:
<input name="date1" id="date1" type="date" data-role="datebox"
data-options='{"mode": "calbox","dateFieldOrder":["d","m","y"],
"useNewStyle":true, "overrideDateFormat": "%d/%m/%Y",
"afterToday":true, "centerHoriz": true, "useFocus": true}' />
Here is your updated FIDDLE
In the fiddle I have also changed your script a little. With the datebox you can set the dates as follows:
var defaultPickerValue = new Date();
$('#date1').datebox('setTheDate', defaultPickerValue).trigger('datebox', {'method':'doset'});
$('#date1').on('change', function () {
if ($('#date2')) {
var temp = new Date();
var start = $('#date1').datebox('getTheDate');
$('#date2').datebox('setTheDate', start).trigger('datebox', {'method':'doset'});
var diff = parseInt((start - temp) / (1000 * 60 * 60 * 24));
diffstrt = (diff * -1) - 1;
$("#date2").datebox("option", {
"minDays": diffstrt
});
}
});
I have fromDate and toDate text boxes and when I select icon beside text boxes Calender will be displayed and when I select a date that date will be displayed in corresponding text boxes.
My intention is to use single generalized function for both toDate and fromDates. How can I do that, I am using YUI Calender and here is my code:
<td>
<strong>From Date</strong>
</td>
<td>
<input type="text" name="fromDate" id="fromDate" value="" size=15>
<img id="calendarFromIcon" src="${resource(dir: "images", file: "calendar_icon.jpg")}" />
<div id="calendarFromContainer"></div>
</td>
<td>
<strong>To Date</strong>
</td>
<td>
<input type="text" name="toDate" id="toDate" value="" size=15>
<img id="calendarToIcon" src="${resource(dir: "images", file: "calendar_icon.jpg")}" />
<div id="calendarToContainer"></div>
</td>
and the script for this is:
var myFromCalendar = new YAHOO.widget.Calendar("calendarFromContainer", {
close: true,
navigator: true
});
myFromCalendar.render();
myFromCalendar.hide();
function handleSelect(type, args, obj) {
var dates = args[0];
var date = dates[0];
var year = date[0];
month = date[1];
month = (month < 10) ? "0" + month : month;
day = date[2];
day = (day < 10) ? "0" + day : day;
var txtDate1 = document.getElementById("fromDate");
txtDate1.value = year+ "/"+ month + "/" + day;
myFromCalendar.hide();
}
myFromCalendar.selectEvent.subscribe(handleSelect,myFromCalendar, true);
YAHOO.util.Event.addListener("calendarFromIcon", "click", function(e) {
var calContainer = YAHOO.util.Dom.get("calendarFromContainer");
var selectedDate = document.getElementById("fromDate");
if (selectedDate.value) {
var matches = selectedDate.value.match(/^\s*0?(\d+)\/0?(\d+)\/(\d+)\s*$/);
var year = parseInt(matches[3]);
var month = parseInt(matches[1]);
var pageDate = month+"/"+year;
myFromCalendar.cfg.setProperty("pagedate", pageDate, false);
myFromCalendar.cfg.setProperty("selected", selectedDate.value, false);
myFromCalendar.render();
}
myFromCalendar.show();
});
You can use jquery to apply a single function to multiple HTML elements. Jqueries select function may help you.