There are many threads here for similar issues that I have read through and tried to apply to my situation being very new to all of this I haven't been able to figure it out I am afraid and was hoping for a little help
I need 2 instances of datepicker on my form with the javeascript alert if certain dates are selected. Using an example that i have found I am able to get one working but am unable name the other datepicker something unique in order to have the second one working as well
$(window).load(function(){
var Event = function (text, className) {
this.text = text;
this.className = className;
};
var events = {};
events[new Date("02/07/2014")] = new Event("Event01", "highlight");
events[new Date("02/26/2014")] = new Event("Event02", "highlight");
events[new Date("02/27/2014")] = new Event("Event03", "highlight");
$("#datepicker").datepicker({
beforeShowDay: function (date) {
var event = events[date];
if (event) {
return [true, event.className, event.text];
} else {
return [true, '', ''];
}
},
onSelect: function (date) {
var event = events[new Date(date)];
if (event) {
alert(event.text)
}
}
});
});//]]>
</script>
<body>
<input type="text" id="datepicker">
<input type="text" id="datepicker2">
</body>
Any help gratefully received
If you want to apply the same functions to both datepickers then you would be better off assigning them a class and using that to control them.
<input type="text" class="datepicker" />
$(".datepicker").datepicker({
beforeShowDay: function (date) {
var event = events[date];
if (event) {
return [true, event.className, event.text];
} else {
return [true, '', ''];
}
},
onSelect: function (date) {
var event = events[new Date(date)];
if (event) {
alert(event.text)
}
}
});
Related
I am trying to bind the value=".."-attribute from an <input>-field to a JsViews observable, so that changes made from a JS datepicker will get detected by the JsView framework.
Example
On initial rendering, the data-linked observedDate parameter is displayed in the <input>-field:
<input class="flatpickr-calendar" type="text" data-link="observedDate">
Then, selecting a new date using the flatpickr javascript tool, the new date will be stored in the value=".."-field:
<input class="flatpickr-calendar" type="text" data-link="observedDate" value="2017-05-09">
The problem
There is now a divergence between the date handled by observedDate and the value-attribute:
JsViews does not detect the change in the value-attribute.
Does anyone have some suggestion as of how to handle this situation? Thanks.
You need an event onChange update value observedDate.
For example, you can do so:
$(".flatpickr").flatpickr({
onChange: function(selectedDates, dateStr, instance) {
$.observable($.view(this.input).data).setProperty("observedDate", dateStr);
},
});
full code.
Update
Or you can create custom tag:
$.views.tags({
flatpickr: {
template: "<input/>",
onUpdate: false,
dataBoundOnly: true,
flatpickr: null,
isChange: false,
changeEvent: function (selectedDates, dateStr, instance) {
this.isChange = true;
this.update(dateStr);
this.isChange = false;
},
onDispose: function () {
if (this.flatpickr) {
this.flatpickr.destroy();
}
},
onAfterLink: function (tagCtx, linkCtx) {
var tag = this;
var props = tagCtx.props;
var options = {
defaultDate: tagCtx.args[0]
};
if (tag._.unlinked) {
if (!tag.linkedElem) {
tag.linkedElem = tag._.inline ? tag.contents("*").first() : $(linkCtx.elem);
}
$.each(props, function (key, prop) {
var option;
if (key.charAt(0) === "_") {
key = key.slice(1);
options[key] = prop;
}
});
options.onChange = $.proxy(tag.changeEvent, tag);
this.flatpickr = tag.linkedElem.flatpickr(options);
} else {
if (!this.isChange) {
this.flatpickr.setDate(options.defaultDate)
}
}
}
}
});
And use:
{^{flatpickr observedDate /}}
full code
Support flatpickr options:
{^{flatpickr observedDate _inline=true _maxDate='2018-05-01' _minDate='2017-05-01'/}}
full code
I'm trying to make a simple calculator for rent arrears, so that as soon as the user types in their values, the "results" section of the table will auto-fill with their results.
At the moment when the user fills in their details, the results section just remains as it was before; however when I de-bug the code, it tells me that there are no errors. I'm pretty sure that the problem is in my event handlers, but I can't work out where/why.
Here is the code:
$(document).ready(function () {
$("#date1").datepicker({
}).on("change", function (e) {
dataBind();
});
$("#date2").datepicker({
}).on("change", function (e) {
dataBind();
});
$(document).on("change", "table input", function () {
dataBind();
});
$("#r1").click(function () {
dataBind();
});
$("#r2").click(function () {
dataBind();
});
$("#r3").click(function () {
dataBind();
});
});
Where date1 and date2 are datepickers, and r1, r2, and r3 are radio buttons.
dataBind is a function which carries out the calculations and updates the results field:
var dataBind = function () {
var config = {
dueDate: new Date($('#date1').val()),
untilDate: new Date($('#date2').val()),
rentAmount: $('#rentAmount').val(),
dueDateResult: $('#date1'),
calcUntilResult: $('#date2')
};
t = new workings(config);
$("#dueDateFirstMissed").html(t.dueDateFirstPaymentResult);
$("#untilDateCalculate").html((t.calculatedUntil));
$("#numberDays").html(t.numberDays.toFixed(0));
$("#numberperiods").html((t.numberPeriods));
$("#amountDue").html("£" + (t.amountDue.toFixed(2)));
$("#dailyRate").html("£" + ((t.dailyRate).toFixed(2)));
};
Here is a link to the fiddle although bear in mind that I haven't finished writing the calculations!
Any help/pointers would be so gratefully appreciated!
Thanks in advance
In your JSFiddle, you have a typo in your getNumberPeriods function, where firsyDate.getMonth() should be firstDate.getMonth(). Rectifying this seems to resolve the issue.
As a sidenote, I would also keep in mind the possibility that someone enter a value that isn't a number in your "Amount of rent due" field. Doing so currently yields NaN in your UI.
Good luck!
There was a syntax error in your variable assigned in below function
function getNumberPeriods() {
var periodLength = getPeriodLength();
var calcDate = (options.untilDate);
var calcYear = calcDate.getFullYear();
var calcMonth = calcDate.getMonth();
var calcDay = calcDate.getDate();
var firstDate = (options.dueDate);
var firstYear = firstDate.getFullYear();
var firstMonth = firstDate.getMonth(); //this was firsyDate.getMonth()
var firstDay = firstDate.getDate();
.....
}
DEMO
UPDATE
You can change your values when you fill all the 3 fields or else you will get NaN in your result and you can do it as below:
var dataBind = function () {
if($("#date1").val()!="" && $("#date2").val()!="" && $('#rentAmount').val()!="")
{ //If all the fields have values then get it done
var config = {
dueDate: new Date($('#date1').val()),
untilDate: new Date($('#date2').val()),
rentAmount: $('#rentAmount').val(),
dueDateResult: $('#date1'),
calcUntilResult: $('#date2')
};
console.log(config);
t = new workings(config);
$("#dueDateFirstMissed").html(t.dueDateFirstPaymentResult);
$("#untilDateCalculate").html((t.calculatedUntil));
$("#numberDays").html(t.numberDays.toFixed(0));
$("#numberperiods").html((t.numberPeriods));
$("#amountDue").html("£" + (t.amountDue.toFixed(2)));
$("#dailyRate").html("£" + ((t.dailyRate).toFixed(2)));
}
};
Note : You haven't given id to your rentAmount textbox at top Just add it too
Updated demo
I have created a function that gives current UTC date and time:
get_current_UTCDate: function() {
var d = new Date();
return d.getUTCFullYear() +"-"+ (d.getUTCMonth()+1) +"-"+d.getUTCDate()+" "+_.str.sprintf("%02d", d.getUTCHours())+":"+_.str.sprintf("%02d", d.getUTCMinutes())+":"+_.str.sprintf("%02d", d.getUTCSeconds());
that has been called into another function :
on_timer: function(e) {
var self = this;
if ($(e.target).hasClass("pt_timer_start")) {
current_date = this.get_current_UTCDate();
this.set_current_timer_activity({date: current_date});
this.start_interval();
}
And this on_timer function is called into a toggle button.
this.$el.find(".pt_timer_button button").on("click", this.on_timer);
The problem:
On each time when i press start button it takes new value from current_date.
And my condition is, if button is pressed for 1st time than take FRESH value from current_date, And if page is refreshed and button is again pressed then it should take that FIRST value. (It should not take another fresh value).
So is there any way to store first value of current_date into some another variable X, and let it keep static. Or may I use cookies?
Thanks in advance .
This code demonstrates the basic functionality you need (I only used part of your code)...
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
obj = {
get_current_UTCDate: function() {
var d = new Date();
return d.getUTCFullYear() +"-"+ (d.getUTCMonth()+1) +"-"+d.getUTCDate()+" "+ d.getUTCHours()+":"+ d.getUTCMinutes()+":"+ d.getUTCSeconds();
},
on_timer: function() {
if (localStorage.getItem("curdate") == null) {
localStorage.setItem("curdate",obj.get_current_UTCDate());
alert('first time');
}
alert(localStorage.getItem("curdate"));
}
}
$(document).ready(function(){
$('button').on("click", obj.on_timer);
});
</script>
</head>
<body>
<button>click</button>
</body>
</html>
Without knowing all of the requirements I would look into using a cookie to store the value. Since you are already using jQuery you could use the $.cookie plugin, or just use a basic set/get routine like:
function cookies() {
return document.cookie.split('; ').reduce(function(acc, v) {
p = v.split('='); acc[p[0]] = p[1]; return acc;
}, {});
}
function getCookie(key) {
return cookies()[key];
}
function setCookie(key, value) {
return document.cookie = [key, '=', value, ';'].join('');
}
Then in your code something like:
if ($(e.target).hasClass("pt_timer_start")) {
if (saved_date = getCookie('current_date')) {
current_date = saved_date;
} else {
current_date = this.get_current_UTCDate();
setCookie('current_date', current_date);
}
this.set_current_timer_activity({date: current_date});
this.start_interval();
}
dateContainer.datepicker({
defaultDate: this.filterValue,
changeMonth: true,
changeYear: true,
dateFormat: 'MM-dd-yyyy',
onSelect: function (dateText, t) {
var type = $context.container.find(".grid-filter-type").val();
$context.cb(type, dateText);
}
});
I'm using gridmvc.js and bootstrap-datepicker.js plugin.
OnSelect event is not firing anyway. I don't know what is the reason ?
I don't know because of what, the problem is occurred. But I've found the temporary solution for this. For the solution, you've to change one line of code in bootstrap-datepicker.js. (Check about the license before you change and use the plugin)
case 'span':
if (!target.is('.disabled')) {
this.viewDate.setUTCDate(1);
if (target.is('.month')) {
var day = 1;
var month = target.parent().find('span').index(target);
var year = this.viewDate.getUTCFullYear();
this.viewDate.setUTCMonth(month);
this._trigger('changeMonth', this.viewDate);
if (this.o.minViewMode === 1) {
this._setDate(UTCDate(year, month, day,0,0,0,0));
}
} else {
var year = parseInt(target.text(), 10)||0;
var day = 1;
var month = 0;
this.viewDate.setUTCFullYear(year);
this._trigger('changeYear', this.viewDate);
if (this.o.minViewMode === 2) {
this._setDate(UTCDate(year, month, day,0,0,0,0));
}
}
this.showMode(-1); this.fill();
Here the problem is occured because of this.fill() is called.
if you comment this line in plugin, datepicker won't hide any way on month and year change. Or you can change by following,
if (target.is('.month')) {
if (!this._o.changeMonth) {
this.fill();
}
}
else {
if (!this._o.changeYear) {
this.fill();
}
}
Then this will work, based on the parameter you've given while creating datepicker.
Hi I have a JQuery plugin that takes an array of Orders and creates rows for each Order in the array. No issues here. However if one of these Orders meets a condition it should add a textbox in one of the TD cells. When I debug I can see it adding the textBox but when the next row is created which requires a textBox the previous textbox gets removed. i have this inside a close so not sure what to do. So the result is I only get textboxes in the last row.
If I add the textBox as html it works fine but I want it as a plugin as I need to bind several events KeyUp/Down MouseWheel, Click. etc
The textbox plugin control (gep_inputcontrol) just creates the html and binds events, nothing fancy.
Any help appreciated.
var _table = $('#orderTable', this);
for (var i = 0; i < params.orders.length; i++) {
var row = createRow(params.orders[i]);
_table.append(row);
}
function createRow(order){
var unmatchedStake = (order.requestedStake - order.matchedStake);
var partMatched = (unmatchedStake > 0);
var tr = $(String.format('<tr id="order_{0}" class="{1}"/>' ,order.orderId, ((i % 2) == 0) ? 'gep-altrow' : 'gep-row'));
tr.append(String.format('<td class="gep-icon gep-status">{0}</td>', order.orderStatusId));
tr.append(String.format('<td class="gep-selectionname">{0} {1} {2}</td>', GBEUtils.getEventName(order.eventClassifierFullName()), gep._settings.resources.general.polarity[order.polarityId], order.selectionName()));
tr.append(String.format('<td class="gep-odds betSlipRowPrice">{0}</td>', order.averageMatchedPrice));
tr.append(String.format('<td class="gep-unmatched betSlipRowStake">{0}</td>', com.base.formatDecimal(order.requestedStake - order.matchedStake,2)));
tr.append(String.format('<td class="gep-matched">{0}</td>', com.base.formatDecimal(order.matchedStake,2)));
tr.append(String.format('<td class="gep-action"><span class="gep-icon"/></td>', order.orderStatusId));
//var tablerow = $(String.format('#order_{0}',order.orderId), _table);
//(function (_table, tr, i, unmatchedStake, tablerow) {
if(unmatchedStake > 0)//part matched
{
$('.gep-unmatched', tr).gep_inputcontrol({
type:'STAKE',
ccSymbol:clientObject.state.ccSymbol,
value: unmatchedStake,
decimalValue:unmatchedStake,
onMouseWheeled: function(e, ev){
gep.inputControlWheeled(e, ev);
gep.calculateRowProfit(e, false);
return false;
},
onArrowClicked: function(e){
gep.onArrowClick(e);
return false;
}
});
//$('.gep-unmatched', tr).html($('.gep-unmatched', tr).html());
$('.gep-odds', tr).gep_inputcontrol({
type:'PRICE',
value:order.requestedPrice,
decimalValue:order.requestedPrice,
onMouseWheeled: function(e, ev){
gep.inputControlWheeled(e, ev);
gep.calculateRowProfit(e, false);
return false;
},
onArrowClicked: function(e){
gep.onArrowClick(e);
return false;
}
});
$('.gep-action .gep-icon', tr).addClass("gep-icon-delete");
$('.gep-icon-delete', tr).bind("click", function(){
alert("delete");
toggleCurrentBetSlipBet(this);
return false;
});
}
// })(_table, tr, i, unmatchedStake, tablerow);
return tr;
}
The textbox plugin creates a table with input box and two anchor tags.
/********************
GEP.gep_inputcontrol // stake input, price input box
********************/
(function ($) {
var _templatePrice = $('<table class="gep-inputcontrol" cellpadding="0" cellspacing="0"><tr><td rowspan="2"><input type="text" size="5" class="gep-inputcontrol-price" /></td><td><a tabindex="-1" href="javascript:void(0);" class="gep-inputup"></a></td></tr><tr><td> <a tabindex="-1" href="javascript:void(0);" class="gep-inputdown"></a> </td></tr></table>');
var _templateStake = $('<table class="gep-inputcontrol" cellpadding="0" cellspacing="0"><tr><td rowspan="2"><span class="gep-ccsymbol" /> <input type="text" size="5" class="gep-inputcontrol-stake" /> </td> <td> <a tabindex="-1" href="javascript:void(0);" class="gep-inputup"></a></td></tr><tr><td> <a tabindex="-1" href="javascript:void(0);" class="gep-inputdown"></a> </td></tr> </table>');
var _template;
var _settings = null;
var _instance;
var methods = {
init: function (options) {
_settings = options;
//options.type = 'STAKE'or 'PRICE'
_template = (options.type == 'STAKE')? _templateStake: _templatePrice;
$('.gep-ccsymbol',_template).html(options.ccSymbol);
this.html(_template);
$('input', this).attr('value', options.value);
$('input', this).attr('initialvalue', options.decimalValue);
$('input', this).attr('decimalValue', options.decimalValue);
$('input', this).bind("mousewheel", function (ev) {
_settings.onMouseWheeled.call(null, this, ev.originalEvent);
});
$('.gep-inputup', this).bind("click", function (e) {
_settings.onArrowClicked.call(null, this);
});
$('.gep-inputdown', this).bind("click", function (e) {
_settings.onArrowClicked.call(null, this);
});
_instance = this;
return this;
},
show: function (params) {
alert("show" + params);
},
hide: function () {
// GOOD
},
update: function (content) {
// !!!
}
};
$.fn.gep_inputcontrol = function (method) {
// Method calling logic
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.gep_inputcontrol');
}
};
})(jQuery);
To elaborate a bit more, I did some small unit tests
This works..
$('.gep-odds', clientObject.liveBetsPane).gep_inputcontrol({
type: 'PRICE',
value: 5,
decimalValue: 5,
onMouseWheeled: function (e, ev) {
gep.inputControlWheeled(e, ev);
gep.calculateRowProfit(e, false);
return false;
},
onArrowClicked: function (e) {
gep.onArrowClick(e);
return false;
}
});
This does NOT work...(Only puts TEXT box in last row) But I need to do it this way as I need values of each row.
$('.gep-odds', clientObject.liveBetsPane).each(function () {
$(this).gep_inputcontrol({
type: 'PRICE',
value: 5,
decimalValue: 5,
onMouseWheeled: function (e, ev) {
gep.inputControlWheeled(e, ev);
gep.calculateRowProfit(e, false);
return false;
},
onArrowClicked: function (e) {
gep.onArrowClick(e);
return false;
}
});
});
I removed dollar from the template and it worked fine.
var _templatePrice = $('<table cla...
is now
var _templatePrice = '<table cla...
Although it sets the html for the last row it was moving for the other rows.
Thanks to me.... :)