here is my code
var s;
var AddEvent = {
settings : {
saveButton : $('#uploadfiles1'),
cancelSpeech : $('.cancelSpeech'),
datePicker : $(".datepicker"),
eventName : $('input[name=eventname]'),
eventDate : $('input[name=eventdate]')
},
init:function(s){
s = this.settings;
this.BindEvents();
$('.Wallpapers').addClass('active');
$('input, textarea').placeholder();
},
BindEvents:function(){
this.CancelButton();
this.DatePicker();
// this.SaveButton();
$('input[type=text],textarea').on('keyup change',function(){
AddEvent.FieldsCheck();
});
},
CancelButton: function()
{
s.cancelSpeech.on('click',function(){
var referrer = document.referrer;
window.location = referrer;
});
},
DatePicker :function()
{
s.datePicker.datepicker({
//defaultDate: +7,
showOtherMonths: true,
autoSize: true,
//appendText: '(dd-mm-yyyy)',
dateFormat: 'dd/mm/yy'
});
},
SaveButton: function()
{
this.ClearFields();
},
FieldsCheck: function()
{
alert(s.eventName.attr('name'));
if(s.eventName.val()!='' && s.eventDate.val() !='' && $('textarea').val()!='')
{
s.saveButton.removeAttr('disabled').removeClass('disabled');
}
else
s.saveButton.attr('disabled','disabled').addClass('disabled');
},
ClearFields:function()
{
$('input,textarea').val('');
this.FieldsCheck();
}
};
$(function(){
AddEvent.init(s);
});
i am impletenting this example http://css-tricks.com/how-do-you-structure-javascript-the-module-pattern-edition/
but each time when i type in my input field at this line i get undefined in alert
alert(s.eventName.attr('name'));
please tell me what am i doing wrong i tried to search but couldnt find anything usefull.
edit: here i created a little jsfiddle i am getting
TypeError: this.settings is undefined
[Break On This Error]
console.log(this.settings.eventName.attr('id'));
thanks
Your problem is here :
var s;
AddEvent.init(s);
There is no way after this to have s defined.
A solution would be to simply not pass s (and no declare it in the arguments of the function) :
init:function(s){
s = this.settings;
...
AddEvent.init();
But that lets a variable polluting the global namespace.
If you want your settings to be accessed from all your functions, you could embed in in a closure :
var AddEvent = (function(){
var settings;
return {
init:function(){
settings = {
saveButton : $('#uploadfiles1'),
cancelSpeech : $('.cancelSpeech'),
datePicker : $(".datepicker"),
eventName : $('input[name=eventname]'),
eventDate : $('input[name=eventdate]')
};
this.BindEvents();
$('.Wallpapers').addClass('active');
$('input, textarea').placeholder();
},
BindEvents:function(){
this.CancelButton();
this.DatePicker();
// this.SaveButton();
$('input[type=text],textarea').on('keyup change',function(){
AddEvent.FieldsCheck();
});
},
CancelButton: function()
{
settings.cancelSpeech.on('click',function(){
var referrer = document.referrer;
window.location = referrer;
});
},
DatePicker :function()
{
settings.datePicker.datepicker({
//defaultDate: +7,
showOtherMonths: true,
autoSize: true,
//appendText: '(dd-mm-yyyy)',
dateFormat: 'dd/mm/yy'
});
},
SaveButton: function()
{
this.ClearFields();
},
FieldsCheck: function()
{
alert(settings.eventName.attr('name'));
if(settings.eventName.val()!='' && settings.eventDate.val() !='' && $('textarea').val()!='')
{
settings.saveButton.removeAttr('disabled').removeClass('disabled');
}
else
settings.saveButton.attr('disabled','disabled').addClass('disabled');
},
ClearFields:function()
{
$('input,textarea').val('');
this.FieldsCheck();
}
}
})();
$(function(){
AddEvent.init();
});
Related
I have an issue. I have set updateViewDate to false. The problem is that when I try to change date with code like this $('#calendar').datepicker('setDate', '2019-12-20'); month view doesn't change, it still shows current (November) month. If updateViewDate is set to true when it works perfectly fine. How to fix this? Full code:
$('#calendar').datepicker({
language: 'lt',
autoclose: true,
templates: {
leftArrow: ' ',
rightArrow: ' '
},
orientation: 'auto',
updateViewDate: false,
beforeShowDay: function (date) {
if(enabledDates.hasOwnProperty(date.toLocaleDateString('lt-LT'))) {
return {
enabled: true,
classes: ((enabledDates[date.toLocaleDateString('lt-LT')] > 0 ? 'reservation-date' : 'full-reserved-date'))
};
} else {
return false;
}
}
}).on('changeDate', function(e) {
$('.free-times').html('');
lastSelectedDate = e.format();
$.get('/reservation/short-term/get-free-times',
{
selectedDate: lastSelectedDate,
premiseId: premiseId,
userSelectedTimes: Object.keys(userSelectedTimes)
}, function(data) {
$('.free-times').html(data);
$('[data-toggle="tooltip"]').tooltip();
});
}).on('changeMonth', function(e) {
var selectedDate = e.date.toLocaleDateString('lt-LT');
$.get('{{ route('reservation.update-calendar') }}',
{
selectedDate: selectedDate,
premiseId: premiseId,
}, function(data) {
enabledDates = data;
$('#calendar').datepicker('update');
if(lastSelectedDate) {
$('#calendar').datepicker('setDate', lastSelectedDate);
}
});
});
Thanks for help in advance!
P.S Tried $('#calendar').datepicker('_setDate', lastSelectedDate, 'view'); it kind of works, but I want that after this function call changeMonth method would be called (Only if that month is different than current)
I'm working on odoo9,I have a date field in my model, I want to enable only Mondays in its calendar, I found Jquery solutions on google and applied to my date field but could not get the desired result. Instead I get two calendars , second one is shown when I continue to press left click on my date field.See second Image.
Second image.
This is my Jquery code:
$('.o_datepicker_input').datepicker({
beforeShowDay: function (date)
{
return [(date.getDay() == 1), ""];
},
});
try this
$(".week").datepicker("option", {
beforeShowDay: function (date)
{
return [date.getDay() == 1, ''];
}
});
var weekOptions = { "changeMonth": false, "changeYear": false, "stepMonths": 0,
beforeShowDay: function (date) {
return [date.getDay() == 1, ''];
}
};
$(function () {
$(".week").datepicker("option", weekOptions);
});
Here is the answer. Little bit tricky.
odoo.define('automation.saturday_datepicker', function (require) {
"use strict";
var core = require('web.core');
var formats = require('web.formats');
var time = require('web.time');
var Widget = require('web.Widget');
var _t = core._t;
`enter code here`var DateWidget = Widget.extend({
template: "web.datepicker",
type_of_date: "date",
events: {
'dp.change': 'change_datetime',
'dp.show': 'set_datetime_default',
'change .o_datepicker_input': 'change_datetime',
},
init: function(parent, options) {
this._super.apply(this, arguments);
var l10n = _t.database.parameters;
this.name = parent.name;
this.options = _.defaults(options || {}, {
pickTime: this.type_of_date === 'datetime',
useSeconds: this.type_of_date === 'datetime',
startDate: moment({ y: 1900 }),
endDate: moment().add(200, "y"),
calendarWeeks: true,
icons: {
time: 'fa fa-clock-o',
date: 'fa fa-calendar',
up: 'fa fa-chevron-up',
down: 'fa fa-chevron-down'
},
language : moment.locale(),
format : time.strftime_to_moment_format((this.type_of_date === 'datetime')? (l10n.date_format + ' ' + l10n.time_format) : l10n.date_format),
daysOfWeekDisabled: [0, 1,2,3,4,5],
});
},
start: function() {
this.$input = this.$('input.o_datepicker_input');
this.$el.datetimepicker(this.options);
this.picker = this.$el.data('DateTimePicker');
this.set_readonly(false);
this.set_value(false);
},
set_value: function(value) {
this.set({'value': value});
this.$input.val((value)? this.format_client(value) : '');
this.picker.setValue(this.format_client(value));
},
get_value: function() {
return this.get('value');
},
set_value_from_ui: function() {
var value = this.$input.val() || false;
this.set_value(this.parse_client(value));
},
set_readonly: function(readonly) {
this.readonly = readonly;
this.$input.prop('readonly', this.readonly);
},
is_valid: function() {
var value = this.$input.val();
if(value === "") {
return true;
} else {
try {
this.parse_client(value);
return true;
} catch(e) {
return false;
}
}
},
parse_client: function(v) {
return formats.parse_value(v, {"widget": this.type_of_date});
},
format_client: function(v) {
return formats.format_value(v, {"widget": this.type_of_date});
},
set_datetime_default: function() {
//when opening datetimepicker the date and time by default should be the one from
//the input field if any or the current day otherwise
var value = moment().second(0);
if(this.$input.val().length !== 0 && this.is_valid()) {
value = this.$input.val();
}
// temporarily set pickTime to true to bypass datetimepicker hiding on setValue
// see https://github.com/Eonasdan/bootstrap-datetimepicker/issues/603
var saved_picktime = this.picker.options.pickTime;
this.picker.options.pickTime = true;
this.picker.setValue(value);
this.picker.options.pickTime = saved_picktime;
},
change_datetime: function(e) {
if(this.is_valid()) {
this.set_value_from_ui();
this.trigger("datetime_changed");
}
},
commit_value: function() {
this.change_datetime();
},
destroy: function() {
this.picker.destroy();
this._super.apply(this, arguments);
},
});
var DateTimeWidget = DateWidget.extend({
type_of_date: "datetime"
});
return {
DateWidget: DateWidget,
DateTimeWidget: DateTimeWidget,
};
});
odoo.define('web.form_widgets_custom', function (require) {
"use strict";
var core = require('web.core');
var common = require('web.form_common');
var formats = require('web.formats');
var automation_saturday_date_picker = require('automation.saturday_datepicker')
var _t = core._t;
var QWeb = core.qweb;
var FieldDatetime = core.form_widget_registry.get('datetime')
var FieldDate = FieldDatetime.extend({
template: "FieldDate",
build_widget: function() {
return new automation_saturday_date_picker.DateWidget(this);
}
});
core.form_widget_registry
.add('saturday_date_widget', FieldDate)
});
And finally give widget="saturday_date_widget" to model's field in xml.
JavaScript :
$http.get("/getApexBody", config).then(function(response) {
document.getElementById("saveBtn").disabled = false;
document.getElementById("cleanBtn").disabled = false;
$scope.apexClassWrapper = response.data;
$('#loaderImage').hide();
if (globalEditor1) {
globalEditor1.toTextArea();
}
setTimeout(function(test) {
CodeMirror.commands.autocomplete = function(cm) {
cm.showHint({
hint: CodeMirror.hint.auto
});
};
var editor = CodeMirror.fromTextArea(document.getElementById('apexBody'), {
lineNumbers: true,
matchBrackets: true,
extraKeys: {
"Ctrl-Space": "autocomplete"
},
gutters: ["CodeMirror-lint-markers"],
lint: true,
mode: "text/x-apex"
});
globalEditor1 = $('.CodeMirror')[0].CodeMirror;
}), 2000
});
This is my JS file, the ctrl-space works fine but I need, to implement autocomplete without any key bindings.
I have even tried this :
$http.get("/getApexBody", config).then(function(response) {
document.getElementById("saveBtn").disabled = false;
document.getElementById("cleanBtn").disabled = false;
$scope.apexClassWrapper = response.data;
$('#loaderImage').hide();
if (globalEditor1) {
globalEditor1.toTextArea();
}
setTimeout(function(test) {
/* CodeMirror.commands.autocomplete = function(cm) {
cm.showHint({
hint: CodeMirror.hint.auto
});
};*/
var editor = CodeMirror.fromTextArea(document.getElementById('apexBody'), {
lineNumbers: true,
matchBrackets: true,
/*extraKeys: {
"Ctrl-Space": "autocomplete"
},*/
gutters: ["CodeMirror-lint-markers"],
lint: true,
mode: "text/x-apex"
});
editor.on('inputRead', function onChange(editor, input) {
if (input.text[0] === ';' || input.text[0] === ' ') {
return;
}
CodeMirror.commands.autocomplete = function(editor) {
editor.showHint({
hint: CodeMirror.hint.auto
});
};
});
globalEditor1 = $('.CodeMirror')[0].CodeMirror;
}), 2000
});
But this is not working.
Is there something I am missing here? How can I show live completion hints with codemirror?
I have used show-hints.js , and have modified it a bit to work for "." too.
Please help.
Use this function to autocomplete codeMirror without CTRL + Space.
Set completeSingle to false in the show-hint.js
editor.on("inputRead", function(instance) {
if (instance.state.completionActive) {
return;
}
var cur = instance.getCursor();
var token = instance.getTokenAt(cur);
if (token.type && token.type != "comment") {
CodeMirror.commands.autocomplete(instance);
}
});
$http.get("/getApexBody", config).then(function(response) {
document.getElementById("saveBtn").disabled = false;
document.getElementById("cleanBtn").disabled = false;
$scope.apexClassWrapper = response.data;
$('#loaderImage').hide();
if (globalEditor1) {
globalEditor1.toTextArea();
}
setTimeout(function(test) {
/*CodeMirror.commands.autocomplete = function(cm) {
cm.showHint({
hint: CodeMirror.hint.auto
});
};*/
var editor = CodeMirror.fromTextArea(document.getElementById('apexBody'), {
lineNumbers: true,
matchBrackets: true,
styleActiveLine: true,
extraKeys: {
".": function(editor) {
setTimeout(function() {
editor.execCommand("autocomplete");
}, 100);
throw CodeMirror.Pass; // tell CodeMirror we didn't handle the key
}
},
gutters: ["CodeMirror-lint-markers"],
lint: true,
mode: "text/x-apex"
});
editor.on('inputRead', function onChange(editor, input) {
if (input.text[0] === ';' || input.text[0] === ' ') {
return;
}
//CodeMirror.commands.autocomplete = function(editor) {
editor.showHint({
hint: CodeMirror.hint.auto
});
//};
});
globalEditor1 = $('.CodeMirror')[0].CodeMirror;
}), 2000
});
This works, but after entering ".", it does gives methods of that particular variable but after entering few more matching words it again starts showing hints from original set of words.
for eg: isBatch and isAbort are two methods of System class.
When I start typing Sy... System comes up, then I type ".", them the two methods shows up isBatch and isAbort, but when I type isA instead of showing isAbort it starts showing hints from full list of words again.
Is there a way to avoid this too?
It is possible to declare 2 more functions in main function like this ?
var jquery4u = {
init: function() {
jquery4u.countdown.show();
},
countdown: function() {
show: function() {
console.log('show');
},
hide: function() {
console.log('hide');
}
}
}
jquery4u.init();
and i receive the following error: Uncaught SyntaxError: Unexpected token ( on this line "show: function() {"
Remove the function from the right of the countdown (demo)
var jquery4u = {
init: function() {
jquery4u.countdown.show();
},
countdown: {
show: function() {
console.log('show');
},
hide: function() {
console.log('hide');
}
}
}
jquery4u.init();
Next time, use jsFiddle to make a demo and click the "JSHint" button.
Actually, none of this will work. Unless you make countdown an object or you treat its sub-functions as proper functions.
Why: Under countdown, you created an instance of object not a function.
var jquery4u = {
countdown: function() {
show = function() {
console.log('show');
}
hide = function() {
console.log('hide');
}
jquery4u.countdown.show();
}
}
The above code is a valid code so it is possible. Unfortunately it will not return anything.
The proper way to do this is in this format:
var jquery4u = {
countdown: {
show: function() {
console.log('show');
},
hide: function() {
console.log('hide');
}
}
}
This will work. You can try it out by calling:
jquery4u.countdown.show();
I've been all over the related questions but couldn't find an answer to my problem.
http://s1308.hizliresim.com/1d/5/r50lw.png
When I click "Kredi Yükle" a popup should appear but nothing happens and i get these console errors.
What should i do?
In related js file :
CreditLoadingAmrEditor = Class.create({
SELECTION_WINDOW : "wndCreditLoadingHelper",
BUTTON_OK : "btnLoadCreditOk",
BUTTON_CANCEL : "btnLoadCreditCancel",
CREDIT_AMOUNT : "fld_credit_amount",
initialize: function(owner) {
this.owner = owner;
this.browser = owner.browser;
this.buttonOk = $(this.BUTTON_OK);
this.buttonCancel = $(this.BUTTON_CANCEL);
this.selectionWindow = this.initializeHelper(this.SELECTION_WINDOW);
var containers = $$("div[id='loadingCreditContainer']");
if (containers && containers.size() > 0) {
this.container = containers[0];
this.editorManager = new EditorManager("loadingCreditContainer");
this.creditAmount = $(this.CREDIT_AMOUNT).instance;
}
this.browser.addToolClickListener(this);
this.buttonOk.observe(iconstants.KEY_CLICK, this.okClick.bindAsEventListener(this));
this.buttonCancel.observe(iconstants.KEY_CLICK, this.closeClick.bindAsEventListener(this));
},
initializeHelper: function(windowName) {
var result = $(windowName);
if (result){
result.remove();
document.body.appendChild(result);
}
return result;
},
toolClick: function(browser, toolType) {
if (toolType == browser.TOOL_LOAD_CREDIT) {
this.show();
}
return false;
},
show: function(callback) {
this.callback = callback;
FSystem.registerWindow(this.selectionWindow, true, true);
},
hide: function() {
FSystem.unregisterWindow(this.selectionWindow);
},
okClick: function() {
if (this.creditAmount.getValue() >= 0) {
this.hide();
this.requestForLoadingCredit();
} else {
window.alert(localize("value_must_greater_than_0"));
}
},
closeClick: function() {
this.hide();
},
requestForLoadingCredit: function() {
FSystem.startWait();
new Ajax.Request(
iconstants.URL_CREDIT_LOADING_AMR,
{
method : iconstants.METHOD_POST,
parameters : {mid:this.browser.getSelectedId(),ca:this.creditAmount.getValue()},
onComplete : this.responseForDeviceReading.bind(this),
onException : null
});
},
responseForDeviceReading: function(transport) {
FSystem.stopWait();
var JSON = transport.responseText.evalJSON();
if (JSON.status == iconstants.AJAX_STATUS_OK){
//if (confirm(JSON.message)) {
window.open(JSON.url, '_newtab', 'width=1280,height=800');
//}
} else {
alert(JSON.message);
}
}
});
Such type of error occur when your object is not initialized. You are trying to access a method of such object which is not initialized. Please check your object initialization.