Date picker sencha touch 2 - datepicker

I am creating a date picker field dynamically. I need to set the picker field value to a textfield. somehow i am unable to retrieve the picker value. The date picker is displayed but the done button is throwing an error saying "Cannot call method "Todatestring" of undefined.
My code is :
case 'date':
var cmp1 = Ext.create('Ext.Button', {
text:'Date:',
ui:'plain',
id:'datepicker',
handler:function () {
var datePicker = Ext.create('Ext.picker.Date', {
dateFormat:'Y-m-d',
id:'picker1',
doneButton:{
listeners:{
// when the done button is tapped, set the value
tap:function (button, event, eOpts) {
console.log('inside done button');
console.log(Ext.getCmp('picker1').getValue());
/* var picker = this.up('datepicker');
picker.fireEvent('change', picker, picker.getValue());*/
console.log('done button');
}
}
}
});
Ext.getCmp('overlayId').add(datePicker);
datePicker.show();
Ext.getCmp('datefield').setValue('');
}
});
Ext.getCmp('overlayId').add({ xtype:'container', padding:10, items:[cmp1] });
var cmp = Ext.create('Ext.field.Text', {
//label:'Date:',
id:'datefield',
listener:{
focus:function () {
console.log('on blue function called');
}
}
});
break;

I think you do not need to override the setValue() function direct. Better approach is to override the applyValue() or/and updateValue() functions.
See http://docs.sencha.com/touch/2-0/#!/guide/class_system for more information about config properties and how apply/update/set pattern does work
Cheers, Oleg

i know its late, but help somebody later, you can use change listener to get selected date value dynamically
datePicker = Ext.create('Ext.picker.Date', {
itemId:'ctsdateselect',
value: new Date(),
yearFrom: 1985,
yearTo : 2050,
listeners: {
change: function (value, eOpts) {
console.log(eOpts);
},
cancel: function (picker) {
Ext.Msg.alert('You hit cancel', '');
}
}
});
datepicker.show();

I had the same problem and it got fixed by setting value config for the datepicker.
To get the new value you actually need to have some initial value. Check this.

Related

Mapbox GL JS: Style is not done loading

I have a map wher we can classically switch from one style to another, streets to satellite for example.
I want to be informed that the style is loaded to then add a layer.
According to the doc, I tried to wait that the style being loaded to add a layer based on a GEOJson dataset.
That works perfectly when the page is loaded which fires map.on('load') but I get an error when I just change the style, so when adding layer from map.on('styledataloading'), and I even get memory problems in Firefox.
My code is:
mapboxgl.accessToken = 'pk.token';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v10',
center: [5,45.5],
zoom: 7
});
map.on('load', function () {
loadRegionMask();
});
map.on('styledataloading', function (styledata) {
if (map.isStyleLoaded()) {
loadRegionMask();
}
});
$('#typeMap').on('click', function switchLayer(layer) {
var layerId = layer.target.control.id;
switch (layerId) {
case 'streets':
map.setStyle('mapbox://styles/mapbox/' + layerId + '-v10');
break;
case 'satellite':
map.setStyle('mapbox://styles/mapbox/satellite-streets-v9');
break;
}
});
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'regions.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
function loadRegionMask() {
loadJSON(function(response) {
var geoPoints_JSON = JSON.parse(response);
map.addSource("region-boundaries", {
'type': 'geojson',
'data': geoPoints_JSON,
});
map.addLayer({
'id': 'region-fill',
'type': 'fill',
'source': "region-boundaries",
'layout': {},
'paint': {
'fill-color': '#C4633F',
'fill-opacity': 0.5
},
"filter": ["==", "$type", "Polygon"]
});
});
}
And the error is:
Uncaught Error: Style is not done loading
at t._checkLoaded (mapbox-gl.js:308)
at t.addSource (mapbox-gl.js:308)
at e.addSource (mapbox-gl.js:390)
at map.js:92 (map.addSource("region-boundaries",...)
at XMLHttpRequest.xobj.onreadystatechange (map.js:63)
Why do I get this error whereas I call loadRegionMask() after testing that the style is loaded?
1. Listen styledata event to solve your problem
You may need to listen styledata event in your project, since this is the only standard event mentioned in mapbox-gl-js documents, see https://docs.mapbox.com/mapbox-gl-js/api/#map.event:styledata.
You can use it in this way:
map.on('styledata', function() {
addLayer();
});
2. Reasons why you shouldn't use other methods mentioned above
setTimeout may work but is not a recommend way to solve the problem, and you would got unexpected result if your render work is heavy;
style.load is a private event in mapbox, as discussed in issue https://github.com/mapbox/mapbox-gl-js/issues/7579, so we shouldn't listen to it apparently;
.isStyleLoaded() works but can't be called all the time until style is full loaded, you need a listener rather than a judgement method;
Ok, this mapbox issue sucks, but I have a solution
myMap.on('styledata', () => {
const waiting = () => {
if (!myMap.isStyleLoaded()) {
setTimeout(waiting, 200);
} else {
loadMyLayers();
}
};
waiting();
});
I mix both solutions.
I was facing a similar issue and ended up with this solution:
I created a small function that would check if the style was done loading:
// Check if the Mapbox-GL style is loaded.
function checkIfMapboxStyleIsLoaded() {
if (map.isStyleLoaded()) {
return true; // When it is safe to manipulate layers
} else {
return false; // When it is not safe to manipulate layers
}
}
Then whenever I swap or otherwise modify layers in the app I use the function like this:
function swapLayer() {
var check = checkIfMapboxStyleIsLoaded();
if (!check) {
// It's not safe to manipulate layers yet, so wait 200ms and then check again
setTimeout(function() {
swapLayer();
}, 200);
return;
}
// Whew, now it's safe to manipulate layers!
the rest of the swapLayer logic goes here...
}
Use the style.load event. It will trigger once each time a new style loads.
map.on('style.load', function() {
addLayer();
});
My working example:
when I change style
map.setStyle()
I get error Uncaught Error: Style is not done loading
This solved my problem
Do not use map.on("load", loadTiles);
instead use
map.on('styledata', function() {
addLayer();
});
when you change style, map.setStyle(), you must wait for setStyle() finished, then to add other layers.
so far map.setStyle('xxx', callback) Does not allowed. To wait until callback, work around is use map.on("styledata"
map.on("load" not work, if you change map.setStyle(). you will get error: Uncaught Error: Style is not done loading
The current style event structure is broken (at least as of Mapbox GL v1.3.0). If you check map.isStyleLoaded() in the styledata event handler, it always resolves to false:
map.on('styledata', function (e) {
if (map.isStyleLoaded()){
// This never happens...
}
}
My solution is to create a new event called "style_finally_loaded" that gets fired only once, and only when the style has actually loaded:
var checking_style_status = false;
map.on('styledata', function (e) {
if (checking_style_status){
// If already checking style status, bail out
// (important because styledata event may fire multiple times)
return;
} else {
checking_style_status = true;
check_style_status();
}
});
function check_style_status() {
if (map.isStyleLoaded()) {
checking_style_status = false;
map._container.trigger('map_style_finally_loaded');
} else {
// If not yet loaded, repeat check after delay:
setTimeout(function() {check_style_status();}, 200);
return;
}
}
I had the same problem, when adding real estate markers to the map. For the first time addding the markers I wait till the map turns idle. After it was added once I save this in realEstateWasInitialLoaded and just add it afterwards without any waiting. But make sure to reset realEstateWasInitialLoaded to false when changing the base map or something similar.
checkIfRealEstateLayerCanBeAddedAndAdd() {
/* The map must exist and real estates must be ready */
if (this.map && this.realEstates) {
this.map.once('idle', () => {
if (!this.realEstateWasInitialLoaded) {
this.addRealEstatesLayer();
this.realEstateWasInitialLoaded = true
}
})
if(this.realEstateWasInitialLoaded) {
this.addRealEstatesLayer();
}
}
},
I ended up with :
map.once("idle", ()=>{ ... some function here});
In case you have a bunch of stuff you want to do , i would do something like this =>
add them to an array which looks like [{func: function, param: params}], then you have another function which does this:
executeActions(actions) {
actions.forEach((action) => {
action.func(action.params);
});
And at the end you have
this.map.once("idle", () => {
this.executeActions(actionsArray);
});
I have created simple solution. Give 1 second for mapbox to load the style after you set the style and you can draw the layer
map.setStyle(styleUrl);
setTimeout(function(){
reDrawMapSourceAndLayer(); /// your function layer
}, 1000);
when you use map.on('styledataloading') it will trigger couple of time when you changes the style
map.on('styledataloading', () => {
const waiting = () => {
if (!myMap.isStyleLoaded()) {
setTimeout(waiting, 200);
} else {
loadMyLayers();
}
};
waiting();
});

kendo-ui autocomplete extend

I'm trying to extend the kendo-ui autocomplete control: I want the search start when te user hit enter, so basically I've to check the user input on keydown event.
I've tried to catch the keydown event with this code:
(function($) {
ui = kendo.ui,
Widget = ui.Widget
var ClienteText = ui.AutoComplete.extend({
init: function(element,options) {
var that=this;
ui.AutoComplete.fn.init.call(this, element, options);
$(this).bind('keydown',function(e){ console.log(1,e); });
$(element).bind('keydown',function(e){ console.log(2,e); });
},
options: {
[...list of my options...]
},
_keydown: function(e) {
console.log(3,e);
kendo.ui.AutoComplete.fn._keydown(e);
}
});
ui.plugin(ClienteText);
})(jQuery);
None of the binded events gets called, only the _keydown, and then I'm doing something wrong and cannot call the autocomplete "normal" keydown event.
I've seen a lot of examples that extend the base widget and then create a composite widget, but I'm not interested in doing that, I only want to add a functionality to an existing widget.
Can someone show me what I'm doing wrong?
Thank you!
What about avoiding the extend and take advantage of build in options and methods on the existing control : http://jsfiddle.net/vojtiik/Vttyq/1/
//create AutoComplete UI component
var complete = $("#countries").kendoAutoComplete({
dataSource: data,
filter: "startswith",
placeholder: "Select country...",
separator: ", ",
minLength: 50 // this is to be longer than your longest char
}).data("kendoAutoComplete");
$("#countries").keypress(function (e) {
if (e.which == 13) {
complete.options.minLength = 1; // allow search
complete.search($("#countries").val());
complete.options.minLength = 50; // stop the search again
}
});
This code actually work:
(function($) {
ui = kendo.ui,
ClienteText = ui.AutoComplete.extend({
init: function(element,options) {
ui.AutoComplete.fn.init.call(this, element, options);
$(element).bind('keydown',function(e){
var kcontrol=$(this).data('kendoClienteText');
if (e.which === 13) {
kcontrol.setDataSource(datasource_clientes);
kcontrol.search($(this).val());
} else {
kcontrol.setDataSource(null);
}
});
},
options: {
name: 'ClienteText',
}
});
ui.plugin(ClienteText);
})(jQuery);
but I don't know if it's the correct way to do it.

Bootstrap datepicker with knockout.js databind

This question is similar to knockoutjs databind with jquery-ui datepicker, but instead of the jQueryUI datepicker, I would like to use one of the Bootstrap datepickers.
The API for the Bootstrap datepicker is different from jquery-ui, and I am having some trouble wrapping my head around making it work with knockout.js. I have created a jsFiddle to try it out.
It seems like the Bootstrap datepicker could be much simpler to use because it does not independently store the date. However, I would like to know how whether the jsFiddle is the appropriate way to use the Bootstrap datepicker widget with knockout.js i.e.
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).datepicker("destroy");
});
},
update: function(element, valueAccessor) {
}
};
Here is a sample of how you could accomplish this with the datepicker that you are using:
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
//when a user changes the date, update the view model
ko.utils.registerEventHandler(element, "changeDate", function(event) {
var value = valueAccessor();
if (ko.isObservable(value)) {
value(event.date);
}
});
},
update: function(element, valueAccessor) {
var widget = $(element).data("datepicker");
//when the view model is updated, update the widget
if (widget) {
widget.date = ko.utils.unwrapObservable(valueAccessor());
if (widget.date) {
widget.setValue();
}
}
}
};
It did not look like there was any destroy functionality, so I removed that piece. This handles the widgets changeDate event to update the view model, when a user changes the date. The update function handles when the view model is changed to update the widget.
If you want to bind the value to a non-observable, then it would take a little more code. Let me know if that is something that you need to support.
http://jsfiddle.net/rniemeyer/KLpq7/
my current version is a mix between the already shown solutions:
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
var unwrap = ko.utils.unwrapObservable;
var dataSource = valueAccessor();
var binding = allBindingsAccessor();
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
$(element).datepicker('update', dataSource());
//when a user changes the date, update the view model
ko.utils.registerEventHandler(element, "changeDate", function (event) {
var value = valueAccessor();
if (ko.isObservable(value)) {
value(event.date);
}
});
},
update: function (element, valueAccessor) {
var widget = $(element).data("datepicker");
var value = ko.utils.unwrapObservable(valueAccessor());
//when the view model is updated, update the widget
if (widget) {
widget.date = value;
if (widget.date) {
widget.setValue();
$(element).datepicker('update', value)
}
}
}};
The accepted answer didn't work for me with the current version of the date picker. The input wasn't being initialized with the value of the observable. I made an updated binding, to which I added this:
$(element).datepicker('update', dataSource());
That seems to do the trick.
Here's an updated fiddle that uses the latest available date picker, Bootstrap, jQuery, and Knockout: http://jsfiddle.net/krainey/nxhqerxg/
Update:
I experienced some difficulty with the date picker not playing nicely with the observable when a user would edit the value in the text field manually. The tool would immediately parse the date, and plug the result into the input field.
If the user tried to edit 10/07/2014, for example, and used the backspace or delete to remove a number (10/0/2014), the resulting value would be parsed immediately and inserted into the text input. If the value was, for a moment, 10/0/2014, the picker would shift the calendar to 09/30/2014, and plug that value into the text field. If I tried to edit the month, and the value was, for a moment, 1/7/2014, the picker would shift to January 7, 2014, and plug that value in to the text field.
You can see that behavior in this fiddle:
http://jsfiddle.net/krainey/nxhqerxg/10/
I had to update my binding with a special handler to detect focus, and bind a one-time blur event to get it to handle manual edits correctly.
$(element).on("changeDate", function (ev) {
var observable = valueAccessor();
if ($(element).is(':focus')) {
// Don't update while the user is in the field...
// Instead, handle focus loss
$(element).one('blur', function(ev){
var dateVal = $(element).datepicker("getDate");
observable(dateVal);
});
}
else {
observable(ev.date);
}
});
The fiddle referenced in the original answer has been updated to reflect this:
http://jsfiddle.net/krainey/nxhqerxg/
Here is what I Ended up
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = {
autoclose: true,
format: 'yyyy-mm-dd',
}
//var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
//when a user changes the date, update the view model
ko.utils.registerEventHandler(element, "changeDate", function (event) {
var value = valueAccessor();
if (ko.isObservable(value)) {
var myDate = event.date;
var month = myDate.getMonth() + 1;
var monthText = month;
if (month < 10)
monthText = "0" + month;
var day1 = parseInt(myDate.getDate());
var dayText = day1;
if (day1 < 10)
dayText = '0' + day1;
value(myDate.getFullYear() + '-' + monthText + '-' + dayText);
}
});
},
update: function (element, valueAccessor) {
var widget = $(element).data("datepicker");
//when the view model is updated, update the widget
if (widget) {
widget.date = ko.utils.unwrapObservable(valueAccessor());
widget.setValue(widget.date);
}
}};
There is a much simpler way to get bootstrap-datepicker.js and knockout.js working together. Typically the initialization of the datepicker inputs is invoked during/after the page load. However when knockout.js updates the value binding, the datepicker is not updated correctly with the new value and so when you focus on the datepicker input it defaults to 01-Jan-2001.
All you have to do is to destroy and reinitialise the datepicker inputs after any knockout.js value bindings are updated as per the ViewModel method below, which sets up a mapped object to be edited.
self.showEditOrderForm = function (data) {
ko.mapping.fromJS(data, self.entity);
self.mode('edit');
$('#edit-dateordered').datepicker('destroy');
$('#edit-dateordered').datepicker({
format: 'dd-M-yyyy',
title: 'Select Date',
weekStart: 1,
todayHighlight: true,
autoClose: true,
endDate: '0d'
});
};

Handle selected event in autocomplete textbox using bootstrap Typeahead?

I want to run JavaScript function just after user select a value using autocomplete textbox bootstrap Typeahead.
I'm searching for something like selected event.
$('.typeahead').on('typeahead:selected', function(evt, item) {
// do what you want with the item here
})
$('.typeahead').typeahead({
updater: function(item) {
// do what you want with the item here
return item;
}
})
For an explanation of the way typeahead works for what you want to do here, taking the following code example:
HTML input field:
<input type="text" id="my-input-field" value="" />
JavaScript code block:
$('#my-input-field').typeahead({
source: function (query, process) {
return $.get('json-page.json', { query: query }, function (data) {
return process(data.options);
});
},
updater: function(item) {
myOwnFunction(item);
var $fld = $('#my-input-field');
return item;
}
})
Explanation:
Your input field is set as a typeahead field with the first line: $('#my-input-field').typeahead(
When text is entered, it fires the source: option to fetch the JSON list and display it to the user.
If a user clicks an item (or selects it with the cursor keys and enter), it then runs the updater: option. Note that it hasn't yet updated the text field with the selected value.
You can grab the selected item using the item variable and do what you want with it, e.g. myOwnFunction(item).
I've included an example of creating a reference to the input field itself $fld, in case you want to do something with it. Note that you can't reference the field using $(this).
You must then include the line return item; within the updater: option so the input field is actually updated with the item variable.
first time i've posted an answer on here (plenty of times I've found an answer here though), so here's my contribution, hope it helps. You should be able to detect a change - try this:
function bob(result) {
alert('hi bob, you typed: '+ result);
}
$('#myTypeAhead').change(function(){
var result = $(this).val()
//call your function here
bob(result);
});
According to their documentation, the proper way of handling selected event is by using this event handler:
$('#selector').on('typeahead:select', function(evt, item) {
console.log(evt)
console.log(item)
// Your Code Here
})
What worked for me is below:
$('#someinput').typeahead({
source: ['test1', 'test2'],
afterSelect: function (item) {
// do what is needed with item
//and then, for example ,focus on some other control
$("#someelementID").focus();
}
});
I created an extension that includes that feature.
https://github.com/tcrosen/twitter-bootstrap-typeahead
source: function (query, process) {
return $.get(
url,
{ query: query },
function (data) {
limit: 10,
data = $.parseJSON(data);
return process(data);
}
);
},
afterSelect: function(item) {
$("#divId").val(item.id);
$("#divId").val(item.name);
}
Fully working example with some tricks. Assuming you are searching for trademarks and you want to get the selected trademark Id.
In your view MVC,
#Html.TextBoxFor(model => model.TrademarkName, new { id = "txtTrademarkName", #class = "form-control",
autocomplete = "off", dataprovide = "typeahead" })
#Html.HiddenFor(model => model.TrademarkId, new { id = "hdnTrademarkId" })
Html
<input type="text" id="txtTrademarkName" autocomplete="off" dataprovide="typeahead" class="form-control" value="" maxlength="100" />
<input type="hidden" id="hdnTrademarkId" />
In your JQuery,
$(document).ready(function () {
var trademarksHashMap = {};
var lastTrademarkNameChosen = "";
$("#txtTrademarkName").typeahead({
source: function (queryValue, process) {
// Although you receive queryValue,
// but the value is not accurate in case of cutting (Ctrl + X) the text from the text box.
// So, get the value from the input itself.
queryValue = $("#txtTrademarkName").val();
queryValue = queryValue.trim();// Trim to ignore spaces.
// If no text is entered, set the hidden value of TrademarkId to null and return.
if (queryValue.length === 0) {
$("#hdnTrademarkId").val(null);
return 0;
}
// If the entered text is the last chosen text, no need to search again.
if (lastTrademarkNameChosen === queryValue) {
return 0;
}
// Set the trademarkId to null as the entered text, doesn't match anything.
$("#hdnTrademarkId").val(null);
var url = "/areaname/controllername/SearchTrademarks";
var params = { trademarkName: queryValue };
// Your get method should return a limited set (for example: 10 records) that starts with {{queryValue}}.
// Return a list (of length 10) of object {id, text}.
return $.get(url, params, function (data) {
// Keeps the current displayed items in popup.
var trademarks = [];
// Loop through and push to the array.
$.each(data, function (i, item) {
var itemToDisplay = item.text;
trademarksHashMap[itemToDisplay] = item;
trademarks.push(itemToDisplay);
});
// Process the details and the popup will be shown with the limited set of data returned.
process(trademarks);
});
},
updater: function (itemToDisplay) {
// The user selectes a value using the mouse, now get the trademark id by the selected text.
var selectedTrademarkId = parseInt(trademarksHashMap[itemToDisplay].value);
$("#hdnTrademarkId").val(selectedTrademarkId);
// Save the last chosen text to prevent searching if the text not changed.
lastTrademarkNameChosen = itemToDisplay;
// return the text to be displayed inside the textbox.
return itemToDisplay;
}
});
});

How to access old and new values before submitting with jeditable

I have a field being updated by jeditable. I want to output a warning message before submitting updates if the value is being reduced (which would result in data being lost), but not if it's being increased.
This seems a good candidate for jeditable's onsubmit function, which I can trigger happily. I can get the new value from $('input', this).val(), but how do I get the original value to which to compare it in this context?
...
Since posting the above explanation / question, I've come up with a solution of sorts. By changing the invokation in jquery.ready from
$('#foo').editable(...);
to
$('#foo').hover(function(){
var old_value = $(this).text();
$(this).editable('ajax.php', {
submitdata {'old_value':old_value}
});
});
I can use settings.submitdata.old_value in the onsubmit method.
But there surely has to be a better way? jeditable must still have the old value tucked away somewhere in order to be able to revert it. So the question becomes how can I access that from the onsubmit function?
Many thanks in advance for any suggestions.
A much easier solution would be to add this line to your submitdata variable
"submitdata": function (value, settings) {
return {
"origValue": this.revert
};
}
Here is my editable (it is using the submitEdit function):
$(function () {
$('.editable').editable(submitEdit, {
indicator: '<img src="content/images/busy.gif">',
tooltip: '#Html.Resource("Strings,edit")',
cancel: '#Html.Resource("Strings,cancel")',
submit: '#Html.Resource("Strings,ok")',
event: 'edit'
});
/* Find and trigger "edit" event on correct Jeditable instance. */
$(".edit_trigger").bind("click", function () {
$(this).parent().prev().trigger("edit");
});
});
In submitEdit origvalue is the original value before the edit
function submitEdit(value, settings) {
var edits = new Object();
var origvalue = this.revert;
var textbox = this;
var result = value;
// sb experiment
var form = $(this).parents('form:first');
// end experiment
edits["field"] = form.find('input[name="field"]').val();
edits["value"] = value;
var returned = $.ajax({
url: '#Url.Action("AjaxUpdate")',
type: "POST",
data: edits,
dataType: "json",
complete: function (xhr, textStatus) {
// sever returned error?
// ajax failed?
if (textStatus != "success") {
$(textbox).html(origvalue);
alert('Request failed');
return;
}
var obj = jQuery.parseJSON(xhr.responseText);
if (obj != null && obj.responseText != null) {
alert(obj.responseText);
$(textbox).html(origvalue);
}
}
});
return (result);
}