jquery- How to Call public method of jquery plugin - javascript

I'm working with a drag and drop plugin . fieldChooser
I want to call a method and an event But I don't know how .
this is the function :
(function($) {
$.fn.fieldChooser = function (sourceList, destinationList, options)
{
var fieldChooser = this;
//----------------------------------------------------------------------
// Poor man's singleton
//----------------------------------------------------------------------
if (this.getOptions)
{
return this;
}
//----------------------------------------------------------------------
// Private methods
//----------------------------------------------------------------------
function getBounds(element)
{
var offset = element.offset();
return {
left: offset.left,
right: offset.left + element.width(),
top: offset.top,
bottom: offset.top + element.height()
}
}
function translateBounds(bounds, newPosition)
{
return {
left: newPosition.left,
right: bounds.right + newPosition.left - bounds.left,
top: newPosition.top,
bottom: bounds.bottom + newPosition.top - bounds.top
}
}
function hitTest(container, element, newPosition)
{
var containerBounds = getBounds(container);
var elementBounds = getBounds(element);
elementBounds = translateBounds(elementBounds, newPosition);
var hit = true;
if (elementBounds.right < containerBounds.left)
{
hit = false;
}
else if (elementBounds.left > containerBounds.right)
{
hit = false;
}
else if (elementBounds.bottom < containerBounds.top)
{
hit = false;
}
else if (elementBounds.top > containerBounds.bottom)
{
hit = false;
}
return hit;
}
var _chooser = this;
var _lastSelectionList = null;
function onListSelectionChanged(event, list)
{
if (_lastSelectionList)
{
if (_lastSelectionList == list)
{
// continue
}
else
{
var otherList = _chooser.getSourceList();
if (list == _chooser.getSourceList())
{
otherList = _chooser.getDestinationList();
}
otherList.clearSelection(true);
}
}
_lastSelectionList = list;
}
//----------------------------------------------------------------------
// fieldList class
//----------------------------------------------------------------------
var fieldList = function (parent, tabIndex)
{
var _list = $(parent);
_list.addClass("fc-field-list");
_list.attr("tabIndex", tabIndex);
var _selectedIndex = -1;
var _extendedSelectionIndex = -1;
var prepareListFields = function (content)
{
content.addClass("fc-field");
content.attr("tabIndex", tabIndex);
content.off("click.field");
content.on("click.field", function (event)
{
event.stopPropagation();
event.preventDefault();
var $this = $(this);
var currentList = _chooser.getFieldList($this);
if (event.ctrlKey || event.metaKey)
{
currentList.toggleFieldSelection($this);
}
else if (event.shiftKey)
{
currentList.selectTo($this);
}
else
{
currentList.selectField($this);
}
_currentList = currentList;
});
};
prepareListFields(_list.children());
_list.selectAt = function (index)
{
this.clearSelection(true);
var fields = _list.getFields();
if (index >= fields.length)
{
index = fields.length - 1;
}
var selectedField = null;
if (index >= 0)
{
selectedField = fields.eq(index);
}
if (selectedField)
{
selectedField.addClass("fc-selected");
_selectedIndex = index;
_list.scrollToField(selectedField);
}
else
{
_selectedIndex = -1;
}
_list.trigger("selectionChanged", [_list]);
}
_list.extendSelection = function (up)
{
var selectedIndex = this.getSelectedIndex();
var extendedIndex = this.getExtendedSelectionIndex();
var newIndex = extendedIndex;
var extend = true;
if (up)
{
if (newIndex < 0)
{
newIndex = _list.getFields().length;
_selectedIndex = newIndex - 1;
}
if (extendedIndex > selectedIndex)
{
extend = false;
}
else
{
newIndex--;
}
}
else
{
if (newIndex < 0)
{
_selectedIndex = 0;
}
if (extendedIndex < selectedIndex)
{
extend = false;
}
else
{
newIndex++;
}
}
var fields = _list.getFields();
if (newIndex < 0 || newIndex >= fields.length)
{
// continue
}
else
{
var selectedField = fields.eq(newIndex);
if (extend)
{
selectedField.addClass("fc-selected");
}
else
{
selectedField.removeClass("fc-selected");
if (up)
{
newIndex--;
}
else
{
newIndex++;
}
if (newIndex >= 0 && newIndex < fields.length)
{
selectedField = fields.eq(newIndex);
}
}
_list.scrollToField(selectedField);
_list.trigger("selectionChanged", [_list]);
_extendedSelectionIndex = newIndex;
}
}
_list.selectField = function (field)
{
this.clearSelection(true);
field.addClass("fc-selected");
_selectedIndex = field.index();
_list.trigger("selectionChanged", [_list]);
}
_list.toggleFieldSelection = function (field)
{
field.toggleClass("fc-selected");
if (field.hasClass("fc-selected"))
{
_selectedIndex = field.index();
_extendedSelectionIndex = -1;
}
else
{
if (_selectedIndex == field.index())
{
_selectedIndex = _list.children(".fc-selected").first().index();
}
}
_list.trigger("selectionChanged", [_list]);
}
_list.selectTo = function (fieldOrIndex)
{
var fieldIndex = fieldOrIndex;
if (typeof fieldOrIndex == "object")
{
fieldIndex = fieldOrIndex.index();
}
if (_selectedIndex == -1)
{
_selectedIndex = 0;
}
var children = _list.children();
if (fieldIndex > _selectedIndex)
{
for (var counter = _selectedIndex;
counter < children.length;
counter++)
{
if (counter <= fieldIndex)
{
children.eq(counter).addClass("fc-selected");
}
else
{
children.eq(counter).removeClass("fc-selected");
}
}
}
else
{
for (var counter = _selectedIndex;
counter >= 0;
counter--)
{
if (counter >= fieldIndex)
{
children.eq(counter).addClass("fc-selected");
}
else
{
children.eq(counter).removeClass("fc_selected");
}
}
}
_extendedSelectionIndex = fieldIndex;
_list.trigger("selectionChanged", [_list]);
}
_list.getSelectedIndex = function ()
{
return _selectedIndex;
}
_list.getExtendedSelectionIndex = function ()
{
var index = _extendedSelectionIndex;
if (index < 0)
{
index = _selectedIndex;
}
return index;
}
_list.getSelection = function ()
{
return this.children(".fc-selected");
}
_list.clearSelection = function (suppressEvent)
{
_selectedIndex = -1;
_extendedSelectionIndex = -1;
this.children().removeClass("fc-selected");
if (suppressEvent)
{
// continue
}
else
{
_list.trigger("selectionChanged", [_list]);
}
};
_list.add = function (content)
{
prepareListFields(content);
content.appendTo(_list);
return _list;
};
_list.getFields = function ()
{
return _list.children();
}
_list.scrollToField = function (field)
{
var listTop = _list.position().top;
var listScrollTop = _list.scrollTop();
var listHeight = _list.height();
var listScrollBottom = listScrollTop + listHeight;
var fieldHeight = field.outerHeight();
var fieldTop = listScrollTop + field.position().top - listTop;
var fieldBottom = fieldTop + fieldHeight;
if (fieldTop < listScrollTop)
{
_list.scrollTop(fieldTop);
}
else if (fieldBottom > listScrollBottom)
{
_list.scrollTop(listScrollTop + (fieldBottom - listScrollBottom));
}
};
_list.sortable({
connectWith: ".fc-field-list",
cursor: "move",
opacity: 0.75,
cursorAt: { left: 5, top: 5 },
helper: function (event, field)
{
if (field.hasClass("fc-selected"))
{
// continue
}
else
{
_list.selectField(field);
}
var helper = fieldChooser.getOptions().helper(_list);
var selection = _list.getSelection().clone();
if (helper)
{
// continue
}
else
{
helper = $("<div/>").append(selection);
}
field.data("selection", selection);
field.siblings(".fc-selected").remove();
return helper;
}
});
return _list;
};
//----------------------------------------------------------------------
// Private variables
//----------------------------------------------------------------------
var _options = $.extend({}, $.fn.fieldChooser.defaults, options);
var tabIndex = parseInt(this.attr("tabIndex"));
if (isNaN(tabIndex))
{
tabIndex = 0;
}
this.removeAttr("tabIndex");
var _sourceList = new fieldList(sourceList, tabIndex).addClass("fc-source-fields");
var _destinationList =
new fieldList(destinationList, tabIndex).addClass("fc-destination-fields");
var _currentList = null;
//----------------------------------------------------------------------
// Public properties
//----------------------------------------------------------------------
this.getOptions = function ()
{
return _options;
};
this.getSourceList = function ()
{
return _sourceList;
};
this.getDestinationList = function ()
{
return _destinationList;
};
this.getFieldList = function (field)
{
var list = _destinationList;
if (field.parent().hasClass("fc-source-fields"))
{
list = _sourceList;
}
return list;
}
//----------------------------------------------------------------------
// Public methods
//----------------------------------------------------------------------
this.destroy = function ()
{
this.getOptions = null;
_sourceList.sortable("destroy");
_destinationList.sortable("destroy");
};
//----------------------------------------------------------------------
// Event handlers
//----------------------------------------------------------------------
_destinationList.on("sortstop", function (event, ui)
{
var selection = ui.item.data("selection");
if (hitTest(_sourceList, ui.item, ui.offset))
{
_currentList = _sourceList;
_sourceList.add(selection);
_destinationList.clearSelection();
_sourceList.trigger("selectionChanged", [_sourceList]);
_chooser.trigger("listChanged", [selection, _sourceList]);
ui.item.after(selection).remove();
}
else if (hitTest(_destinationList, ui.item, ui.offset))
{
ui.item.after(selection).remove();
}
else
{
_destinationList.getSelection().remove();
_sourceList.add(selection);
_sourceList.scrollToField(selection);
_destinationList.clearSelection();
_sourceList.trigger("selectionChanged", [_sourceList]);
_currentList = _sourceList;
_chooser.trigger("listChanged", [selection, _sourceList]);
}
});
_sourceList.on("sortstop", function (event, ui)
{
var selection = ui.item.data("selection");
if (hitTest(_destinationList, ui.item, ui.offset))
{
_currentList = _destinationList;
_destinationList.add(selection);
_sourceList.clearSelection();
_destinationList.trigger("selectionChanged", [_destinationList]);
_chooser.trigger("listChanged", [selection, _destinationList]);
}
else if (hitTest(_sourceList, ui.item, ui.offset))
{
// continue
}
else
{
_sourceList.sortable("cancel");
}
ui.item.after(selection).remove();
});
_destinationList.on("selectionChanged", onListSelectionChanged);
_sourceList.on("selectionChanged", onListSelectionChanged);
_destinationList.on("focusin", function ()
{
_currentList = _destinationList;
});
_destinationList.on("focusout", function ()
{
if (_currentList == _destinationList)
{
_currentList = null;
}
});
_sourceList.on("focusin", function ()
{
_currentList = _sourceList;
});
_sourceList.on("focusout", function ()
{
if (_currentList == _sourceList)
{
_currentList = null;
}
});
$(document).keydown(function (event)
{
if (_currentList)
{
if (event.which == 38)
{ // up arrow
event.stopPropagation();
event.preventDefault();
if (event.shiftKey)
{
_currentList.extendSelection(true);
}
else
{
var selectedIndex = _currentList.getSelectedIndex();
var newIndex = selectedIndex - 1;
if (newIndex < 0)
{
newIndex = 0;
}
_currentList.selectAt(newIndex);
}
}
else if (event.which == 40)
{ // down arrow
event.stopPropagation();
event.preventDefault();
if (event.shiftKey)
{
_currentList.extendSelection(false);
}
else
{
var selectedIndex = _currentList.getSelectedIndex();
var newIndex = selectedIndex + 1;
if (selectedIndex < 0)
{
newIndex = _currentList.getFields().length - 1;
}
_currentList.selectAt(newIndex);
}
}
else if (event.which == 27)
{ // escape
_currentList.selectAt(-1);
}
}
});
return this;
};
//--------------------------------------------------------------------------
// Class defaults
//--------------------------------------------------------------------------
$.fn.fieldChooser.defaults = {
helper: function (list) { return null; }
};
}(jQuery));
I want just 2-3 functions and I don't need other ones .
I want to call getDestinationList() to get the fields inside destinationlist and call selectionChanged() event.
Could you help me ? How can I call them ?
these are the definition codes :
$(document).ready(function () {
var $sourceFields = $("#sourceFields");
var $destinationFields = $("#destinationFields");
var $chooser = $("#fieldChooser").fieldChooser(sourceFields, destinationFields);
});
I'm looking forward to hear from you

Try this:
$chooser.on("listChanged",function(event,selection,list){
//event <- The jQuery event invoking the callback.
//selection <- The field (or set of fields) which has moved.
//list <- The field list to which the selection has moved.
alert("listChanged");
}
Documentation link: https://github.com/mateagar/fieldChooser
I hope this help.

Related

Simplify if else statements through a Javascript Array

I have written some javascript code for a multilanguage site. The code works great but I feel like I have a lot of duplicate code. I was wondering if someone can explain how I can make this simpler or minimized. I have tried to use a forEach(function (item, index) but it does not seem to be working.
This is the original code that works....
(function () {
var lang1 = "/en/"; //default language
var lang2 = "/fr/"; //second language
var lang3 = "/es/"; //third language
var languageSwitcher = document.querySelectorAll("a[href='/languages']").forEach((el) => el.parentNode.classList.add("language-switcher"));
document.querySelector("[data-folder='/languages']").classList.add("language-switcher");
document.querySelectorAll(".language-switcher .header-nav-folder-item").forEach((el) => el.classList.add("languages"));
document.querySelectorAll(".language-switcher .header-menu-nav-item:not(:first-child)").forEach((el) => el.classList.add("languages"));
var languages = document.querySelectorAll(".languages");
var language1 = document.querySelectorAll(".language-switcher .languages a[href*='"+lang1+"']");
var language2 = document.querySelectorAll(".language-switcher .languages a[href*='"+lang2+"']")
var language3 = document.querySelectorAll(".language-switcher .languages a[href*='"+lang3+"']")
var windowURL = window.location.href;
var pageURL = windowURL.split("/")[4];
if (pageURL == undefined) {
for (var i = 0; i < language1.length; i++) {
language1[i].onclick = function () {
var path = lang1 + "home";
this.href = path;
};
}
for (var i = 0; i < language2.length; i++) {
language2[i].onclick = function () {
var path = lang2 + "home";
this.href = path;
};
}
for (var i = 0; i < language3.length; i++) {
language3[i].onclick = function () {
var path = lang3 + "home";
this.href = path;
};
}
} else {
for (var i = 0; i < language1.length; i++) {
language1[i].onclick = function () {
var path = lang1 + pageURL;
this.href = path;
};
}
for (var i = 0; i < language2.length; i++) {
language2[i].onclick = function () {
var path = lang2 + pageURL;
this.href = path;
};
}
for (var i = 0; i < language3.length; i++) {
language3[i].onclick = function () {
var path = lang3 + pageURL;
this.href = path;
};
}
}
document.querySelectorAll(".header-nav-item:not(.language-switcher) a").forEach((el) => el.classList.add("language"));
document.querySelectorAll(".header-menu-nav-item:not(.language-switcher) a").forEach((el) => el.classList.add("language"));
document.querySelectorAll('[data-folder="/languages"] .header-menu-nav-item a').forEach((el) => el.classList.remove("language"));
var languageLinks = document.querySelectorAll(".language");
for (var i = 0; i < languageLinks.length; i++) {
var navURL = languageLinks[i].href;
if (windowURL.indexOf(lang1) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[0].classList.add("active");
if (navURL.indexOf(lang1) != -1) {
languageLinks[i].closest("div").style.display = "block";
} else {
languageLinks[i].closest("div").style.display = "none";
}
} else if (windowURL.indexOf(lang2) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[1].classList.add("active");
if (navURL.indexOf(lang2) != -1) {
languageLinks[i].closest("div").style.display = "block";
} else {
languageLinks[i].closest("div").style.display = "none";
}
} else if (windowURL.indexOf(lang3) != -1) {
if (navURL.indexOf(lang3) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[2].classList.add("active");
languageLinks[i].closest("div").style.display = "block";
} else {
languageLinks[i].closest("div").style.display = "none";
}
} else {
if (navURL.indexOf(lang1) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[0].classList.add("active");
languageLinks[i].closest("div").style.display = "block";
} else {
languageLinks[i].closest("div").style.display = "none";
}
}
}
var active = document.querySelector(".language-switcher .active");
active.closest(".language-switcher").prepend(active);
document.querySelectorAll(".header a").forEach((el) => (el.style.visibility = "visible"));
languageSwitcher.style.display = "flex";
})();
I have attempted to use a forEach function and an array but it is not working.
(function () {
var lang = ["/en/", "/fr/", "/es/"];
document.querySelectorAll("a[href='/languages']").forEach((el) => el.parentNode.classList.add("language-switcher"));
document.querySelector("[data-folder='/languages']").classList.add("language-switcher");
document.querySelectorAll(".language-switcher .header-nav-folder-item").forEach((el) => el.classList.add("languages"));
document.querySelectorAll(".language-switcher .header-menu-nav-item:not(:first-child)").forEach((el) => el.classList.add("languages"));
var languages = document.querySelectorAll(".languages");
var windowURL = window.location.href;
var pageURL = windowURL.split("/")[4];
lang.forEach(function (index, value) {
var language = document.querySelectorAll(".language-switcher .languages a[href*='" + value + "']");
if (pageURL == undefined) {
for (var i = 0; i < language.length; i++) {
language[i].onclick = function () {
var path = value + "home";
this.href = path;
};
}
} else {
for (var i = 0; i < language.length; i++) {
language[i].onclick = function () {
var path = value + pageURL;
this.href = path;
};
}
}
document.querySelectorAll(".header-nav-item:not(.language-switcher) a").forEach((el) => el.classList.add("language"));
document.querySelectorAll(".header-menu-nav-item:not(.language-switcher) a").forEach((el) => el.classList.add("language"));
document.querySelectorAll('[data-folder="/languages"] .header-menu-nav-item a').forEach((el) => el.classList.remove("language"));
var languageLinks = document.querySelectorAll(".language");
for (var j = 0; j < languageLinks.length; j++) {
var navURL = languageLinks[j].href;
if (windowURL.indexOf(value) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[index].classList.add("active");
if (navURL.indexOf(value) != -1) {
languageLinks[j].closest("div").style.display = "block";
} else {
languageLinks[j].closest("div").style.display = "none";
}
} else {
if (navURL.indexOf('/en/') != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[0].classList.add("active");
languageLinks[j].closest("div").style.display = "block";
} else {
languageLinks[j].closest("div").style.display = "none";
}
}
}
document.querySelector(".header").style.visibility = "visible";
var active = document.querySelector(".language-switcher .active");
active.closest(".language-switcher").prepend(active);
});
})();

How can I make daterangepicker dates into a drop down menu?

I am using a tour booking theme. I do not want the dates in the theme reservation calendar to be opened in the form of a calendar and I want to remove the passive dates that appear on the calendar. How should I code for this. Can you help me?
I want to do:I want to do:
on my site:on my site:
calendar plugin:calendar plugin:
(function ($) {
new Vue({
el:'#bravo_tour_book_app',
data:{
id:'',
extra_price:[],
person_types:[],
message:{
content:'',
type:false
},
html:'',
onSubmit:false,
start_date:'',
start_date_html:'',
step:1,
guests:1,
price:0,
max_guests:1,
start_date_obj:'',
duration:0,
allEvents:[],
buyer_fees:[],
},
watch:{
extra_price:{
handler:function f() {
this.step = 1;
},
deep:true
},
start_date(){
this.step = 1;
},
guests(){
this.step = 1;
},
person_types:{
handler:function f() {
this.step = 1;
},
deep:true
},
},
computed:{
total_price:function(){
var me = this;
if (me.start_date !== "") {
var total = 0;
var total_guests = 0;
var startDate = new Date(me.start_date).getTime();
for (var ix in me.allEvents) {
var item = me.allEvents[ix];
var cur_date = new Date(item.start).getTime();
if (cur_date === startDate) {
if (item.person_types != null) {
me.person_types = Object.assign([], item.person_types);
} else {
me.person_types = null
}
me.max_guests = parseInt(item.max_guests);
me.price = parseFloat(item.price);
}
}
// for person types
if (me.person_types != null) {
for (var ix in me.person_types) {
var person_type = me.person_types[ix];
total += parseFloat(person_type.price) * parseInt(person_type.number);
total_guests += parseInt(person_type.number);
}
}else{
// for default
total_guests = me.guests;
total += me.guests * me.price;
}
for (var ix in me.extra_price) {
var item = me.extra_price[ix];
var type_total = 0;
if (item.enable === true) {
switch (item.type) {
case "one_time":
type_total += parseFloat(item.price);
break;
case "per_hour":
if (me.duration > 0) {
type_total += parseFloat(item.price) * parseFloat(me.duration);
}
break;
case "per_day":
if (me.duration > 0) {
type_total += parseFloat(item.price) * Math.ceil(parseFloat(me.duration) / 24);
}
break;
}
if (typeof item.per_person !== "undefined") {
type_total = type_total * total_guests;
}
total += type_total;
}
}
for (var ix in me.buyer_fees) {
var item = me.buyer_fees[ix];
var type_total = 0;
type_total += parseFloat(item.price);
if (typeof item.per_person !== "undefined") {
type_total = type_total * total_guests;
}
total += type_total;
}
return total;
}
return 0;
},
total_price_html:function(){
if(!this.total_price) return '';
return window.bravo_format_money(this.total_price);
},
daysOfWeekDisabled(){
var res = [];
for(var k in this.open_hours)
{
if(typeof this.open_hours[k].enable == 'undefined' || this.open_hours[k].enable !=1 ){
if(k == 7){
res.push(0);
}else{
res.push(k);
}
}
}
return res;
}
},
created:function(){
for(var k in bravo_booking_data){
this[k] = bravo_booking_data[k];
}
},
mounted(){
var me = this;
/*$(".bravo_tour_book").sticky({
topSpacing:30,
bottomSpacing:$(document).height() - $('.end_tour_sticky').offset().top + 40
});*/
var options = {
singleDatePicker: true,
showCalendar: false,
sameDate: true,
autoApply : true,
disabledPast : true,
dateFormat : bookingCore.date_format,
enableLoading : true,
showEventTooltip : true,
classNotAvailable : ['disabled', 'off'],
disableHightLight: true,
minDate:this.minDate,
opens:'left',
isInvalidDate:function (date) {
for(var k = 0 ; k < me.allEvents.length ; k++){
var item = me.allEvents[k];
if(item.start == date.format('YYYY-MM-DD')){
return item.active ? false : true;
}
}
return false;
}
};
if (typeof daterangepickerLocale == 'object') {
options.locale = _.merge(daterangepickerLocale,options.locale);
}
this.$nextTick(function () {
$(this.$refs.start_date).daterangepicker(options).on('apply.daterangepicker',
function (ev, picker) {
me.start_date = picker.startDate.format('YYYY-MM-DD');
me.start_date_html = picker.startDate.format(bookingCore.date_format);
})
.on('update-calendar',function (e,obj) {
me.fetchEvents(obj.leftCalendar.calendar[0][0], obj.leftCalendar.calendar[5][6])
});
});
},
methods:{
handleTotalPrice: function () {
},
fetchEvents(start,end){
var me = this;
var data = {
start: start.format('YYYY-MM-DD'),
end: end.format('YYYY-MM-DD'),
id:bravo_booking_data.id,
for_single:1
};
console.log(data);
$.ajax({
url: bravo_booking_i18n.load_dates_url,
dataType:"json",
type:'get',
data:data,
beforeSend: function() {
$('.daterangepicker').addClass("loading");
},
success:function (json) {
me.allEvents = json;
var drp = $(me.$refs.start_date).data('daterangepicker');
drp.allEvents = json;
drp.renderCalendar('left');
if (!drp.singleDatePicker) {
drp.renderCalendar('right');
}
$('.daterangepicker').removeClass("loading");
},
error:function (e) {
console.log(e);
console.log("Can not get availability");
}
});
},
formatMoney: function (m) {
return window.bravo_format_money(m);
},
validate(){
if(!this.start_date)
{
this.message.status = false;
this.message.content = bravo_booking_i18n.no_date_select;
return false;
}
return true;
},
If what you would like to use is simply a drop down list, why don't you create a simple one as follows?
<select name="availableDates">
<option value="0">Select a date</option>
<?php
//get the available dates from your database (or whatever source)
$getDates = $connection->prepare("select Date from availableDatesTable where hotelID=?");
$getDates->bind_param('i',$hotelID); //you could get the hotel ID via a $_GET variable
//store the results into an array
//loop through the array as follows:
foreach($resultArray as $res)
{
echo '<option value="'.$res.'">'.date('d F Y',$res).'</option>';
}
?>
</select>
Not sure what data source you are using, but this is a suggestion that could hopefully lead to the solution you're seeking.

I'm getting this error Uncaught TypeError: this.getElements is not a function

I look into a few answers but I'm not getting any results, I'm trying to fix this issue "Uncaught TypeError: this.getElements is not a function". This part of the code, full code in the link.
var SIDEBAR = new function() {
this.on = function(nameElement){
this.menu = nameElement;
return this;
};
/*more code*/
this.getElements = function() {
/*more code*/
return [];
};
/*more code*/
this.addElements = function() {
var elementsData = this.getElements();
/*more code*/
};
}();
var sid = SIDEBAR.on('test');
sid.load();
Full code: https://jsfiddle.net/e6shbnsu/
The value of this is determined by how a function is called.
this will point to window in setTimeout. Use .bind to have specified values as this context.
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
function inElectron() {
return navigator.userAgent.indexOf("Electron") != -1;
}
var dataManager = {
getItem: function(key, local) {
if (inElectron() || local == 1)
return localStorage.getItem(key);
else
return sessionStorage.getItem(key);
},
setItem: function(key, item, local) {
if (inElectron() || local == 1)
localStorage.setItem(key, item);
else
sessionStorage.setItem(key, item);
}
};
var SIDEBAR = new function() {
this.on = function(nameElement) {
this.menu = nameElement;
return this;
};
this.load = function() {
this.currentElement = 0;
this.refreshElements();
};
this.setAddElementName = function(name) {
this.addElementName = name;
};
this.setNewElementName = function(name) {
this.newElementName = name;
};
this.getElements = function() {
var elementsData = dataManager.getItem(this.getDataKey);
if (typeof elementsData !== 'undefined' && elementsData !== null) {
return JSON.parse(elementsData);
}
return this.getPreloadData();
};
this.setDataKey = function(key) {
this.dataKey = key;
};
this.getDataKey = function() {
if (this.dataKey) {
return this.dataKey;
}
return "SideBar" + this.menu;
};
this.setPreloadData = function(dataArray) {
this.preloadData = dataArray;
};
this.getPreloadData = function() {
if (typeof this.preloadData !== 'undefined' && this.preloadData !== null) {
return this.preloadData;
}
return [];
};
this.getCurrentElement = function() {
var elementsData = getElements;
return elementsData[currentElement];
};
this.refreshElements = function() {
window.setTimeout(function() {
this.clearElements();
}.bind(this), 1);
//outer `this` context is bound to the handler
window.setTimeout(function() {
this.addElements();
}.bind(this), 2);
};
this.deleteElement = function() {
var newArr = [];
var elementsData = this.getElements();
for (var i = 0, l = elementsData.length; i < l; i++) {
if (i != index) {
newArr.push(elementsData[i]);
}
}
dataManager.setItem(this.getDataKey, JSON.stringify(newArr));
};
this.addElements = function() {
var elementsData = this.getElements();
var menuNode = document.getElementById(this.menu);
console.log(elementsData);
for (var i = 0; i < elementsData.length; i++) {
var li = document.createElement("li");
var div = document.createElement("div");
li.value = i;
div.classList.add("list");
var p = document.createElement("p");
p.id = "textBlock";
p.style.display = "inline";
p.setAttribute("contentEditable", false);
p.appendChild(document.createTextNode(elementsData[i].name));
div.appendChild(p);
var obj = getObject();
console.log(obj);
div.onclick = function(e) {
e.stopImmediatePropagation();
if (this.querySelector("#textBlock").contentEditable == "false") {
this.currentElement = this.parentNode.value;
elementsData = this.getElements();
document.getElementById("prompt").innerHTML = elementsData[this.parentNode.value]["data"];
document.querySelector("#wrapper").classList.toggle("toggled");
}
};
var span2 = document.createElement("span");
span2.id = "deleteMode";
span2.classList.add("glyphicon");
span2.classList.add("glyphicon-minus");
span2.onclick = function(e) {
e.stopImmediatePropagation();
deleteItem(this.parentNode.parentNode.value);
window.setTimeout(this.refreshElements, 1);
};
span2.style.display = "none";
div.appendChild(span2);
var span = document.createElement("span");
span.id = "editMode";
span.classList.add("glyphicon");
span.classList.add("glyphicon-pencil");
span.onclick = function(e) {
e.stopImmediatePropagation();
// get href of first anchor in element and change location
for (var j = 0; j < menuNode.length; j++) {
menuNode[j].classList.add("disabled");
}
this.style.display = "none";
this.parentNode.querySelector("#deleteMode").style.display = "";
this.parentNode.classList.add("editableMode");
this.parentNode.classList.remove("disabled");
var textBlock = this.parentNode.querySelector("#textBlock");
textBlock.setAttribute("contentEditable", true);
this.placeCaretAtEnd(textBlock);
textBlock.onkeydown = function(e) {
if (e.keyCode == 13) {
e.stopImmediatePropagation();
var text = this.innerHTML.replace(" ", '');
text = text.replace("<br>", '');
if (text.length > 0) {
this.innerHTML = text;
elementsData[this.parentNode.parentNode.value]['name'] = text;
dataManager.setItem("IFTeleprompterScripts", JSON.stringify(elementsData));
for (var j = 0; j < menuNode.length; j++) {
menuNode[j].classList.remove("disabled");
}
this.parentNode.classList.remove("editableMode");
this.setAttribute("contentEditable", false);
this.parentNode.querySelector("#editMode").style.display = "";
this.parentNode.querySelector("#deleteMode").style.display = "none";
} else {
return false;
}
} else if (e.keyCode == 8) {
if (textBlock.innerHTML.length - 1 === 0) {
textBlock.innerHTML = " ";
}
}
return true;
};
return false;
};
div.appendChild(span);
li.appendChild(div);
scriptsNode.appendChild(li);
}
var li = document.createElement("li");
var div = document.createElement("div");
var span2 = document.createElement("span");
span2.id = "addMode";
span2.classList.add("glyphicon");
span2.classList.add("glyphicon-plus");
div.appendChild(span2);
var p = document.createElement("p");
p.id = "textBlock";
p.style.display = "inline";
p.setAttribute("contentEditable", false);
if (typeof this.addElementName !== 'undefined' && this.addElementName !== null)
p.appendChild(document.createTextNode(" " + this.addElementName));
else
p.appendChild(document.createTextNode(" Add " + this.menu));
div.appendChild(p);
li.onclick = function(e) {
e.stopImmediatePropagation();
var newPushElementName = "New " + this.menu;
if (typeof this.addElementName !== 'undefined' && this.addElementName !== null) {
newPushElementName = this.addElementName;
}
elementsData.push({
"name": newPushElementName,
"data": ""
});
dataManager.setItem(this.getDataKey, JSON.stringify(elementsData));
this.refreshElements();
};
li.appendChild(div);
menuNode.appendChild(li);
};
this.placeCaretAtEnd = function(el) {
el.focus();
if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
};
}();
var sid = SIDEBAR.on('test');
sid.load();
<ul class="sidebar-nav" id="test">
</ul>

Infinite loop in list iterator

I created a list iterator but when trying traverse a list backward the loop runs infinitely. What I did wrong?
function List() {
this.listSize=0;
this.pos=0;
this.dataStore =[];
this.append = append;
this.currPos = currPos;
this.end = end;
this.front = front;
this.length = length;
this.moveTo = moveTo;
this.next = next;
this.prev = prev;
}
function append(element) {this.dataStore[this.listSize++]=element;}
function currPos() {return this.pos;}
function end() {this.pos = this.listSize-1;}
function front() {this.pos =0;}
function length() {return this.listSize;}
function moveTo(position) {this.pos = position;}
function prev() {if(this.pos > 0) --this.pos;}
function next() {if(this.pos < this.listSize) ++this.pos;}
var names = new List();
names.append("A"); names.append("B"); names.append("C");
for(names.end(); names.currPos() >= 0; names.prev()) {console.log(names.getElement());}
Your loop only terminates when the current list position is less than zero, but your .prev() function won't allow that to happen.
To fix it? Well, that's a matter of opinion, but if you're going to the trouble of implementing a list class you might as well make a native .forEach function:
function forEach(callback) {
for (var i = 0; i < this.listSize; ++i)
callback(this.dataStore[i], i);
}
Then you can do:
names.forEach(function(name) { console.log(name); });
I ran into a similar problem when trying to implement a list ADT from the book "Data Structures and Algorithms" and came to find out that the author re-wrote that section in later versions to look like this:
module.exports = List;
function List() {
this.listSize = 0;
this.pos = 0;
this.dataStore = [];
this.clear = clear;
this.find = find;
this.toString = toString;
this.insert = insert;
this.append = append;
this.remove = remove;
this.front = front;
this.end = end;
this.prev = prev;
this.next = next;
this.length = length;
this.currPos = currPos;
this.moveTo = moveTo;
this.getElement = getElement;
this.length = length;
this.contains = contains;
this.hasNext = hasNext;
this.hasPrevious = hasPrevious;
this.insertIf = insertIf;
}
function append(element) {
this.dataStore[this.listSize++] = element;
}
function find(element) {
for (var i = 0; i < this.dataStore.length; ++i) {
if (this.dataStore[i] === element) {
return i;
}
}
return -1;
}
function remove(element) {
var foundAt = this.find(element);
if (foundAt > -1) {
this.dataStore.splice(foundAt, 1);
--this.listSize;
return true;
}
return false;
}
function length() {
return this.listSize;
}
function toString() {
return this.dataStore;
}
function insert(element, after){
var insertPos = this.find(after);
if(insertPos > -1){
this.dataStore.splice(insertPos+1, 0, element);
++this.listSize;
return true;
}
return false;
}
function clear() {
delete this.dataStore;
this.dataStore = [];
this.listSize = this.pos = 0;
}
function contains(element) {
for (var i = 0; i < this.dataStore.length; ++i) {
if(this.dataStore[i] === element) {
return true;
}
}
return false;
}
function front() {
this.pos = 0;
}
function end() {
this.pos = this.listSize-1;
}
function prev() {
return this.dataStore[--this.pos];
}
function next(){
return this.dataStore[this.pos++];
}
function hasNext(){
if (this.pos > this.listSize -1) {
return false;
} else {
return true;
}
}
function hasPrevious() {
if(this.pos <= 0) {
return false;
} else {
return true;
}
}
function currPos() {
return this.pos;
}
function moveTo(position) {
this.pos = position;
}
function getElement() {
return this.dataStore[this.pos];
}
function insertIf(element) {
var greaterThan = true;
for(this.front(); this.hasNext(); ){
if(this.next() > element) {
greaterThan = false;
break;
}
}
console.log(element);
if(greaterThan){
this.append(element);
return true;
} else {
return false;
}
}
Your loops will then look like this:
for (list.front(); list.hasNext();) {
var listItem = list.next();
if(listItem instanceof Customer) {
console.log(listItem.name + ", " + listItem.movie);
} else {
console.log(listItem);
}
}
This has proven to be a much more reliable implementation so you may want to consider switching to this.
You need to change your for loop to:
for(names.end(); names.currPos() > 0; names.prev())

Javascript Array indexFirst

I build a prototype that handle pages, I successfully add (push), but can get the data, I failed:
var foundImageIndex = Pages.indexFirst(function (item) { if (item.PageID == PageID) return true; });
Here the javascript page handler:
var Pages = new Array();
PageContainer = function () //constructor for the proxy
{
// this._baseURL = url;
};
PageContainer.prototype =
{
AddPage: function (data) {
if (data == null) return;
Pages.push({ PageID: data.PageID, SegmentID: data.SegmentID });
},
GetPage: function (PageID) {
alert('getPage('+PageID+')=' + JSON.stringify(Pages));
var foundImageIndex = Pages.indexFirst(function (item) { if (item.PageID == PageID) return true; });
var dt = { PageID: Pages[foundImageIndex].PageID, SegmentID: Pages[foundImageIndex].SegmentID };
return dt;
}
};
I call from other js as following:
var gPageContainer = new PageContainer();
for (var i = 0; i < SegStruct.SegmentsCount; i++) {
var segRClass = //get from webservice
gPageContainer.AddPage({ PageID: i, SegmentID: segRClass.SegmentID });
}
I trying to call: gPageContainer.GetPage(1); but it failed in GetPage: function (PageID) it returns -1 in:
var foundImageIndex = Pages.indexFirst(function (item) { if (item.PageID == PageID) return true; });
foundImageIndex always -1
why?
Simply add the following before the constructor:
if (typeof Array.prototype.indexFirst == 'undefined') {
Array.prototype.indexFirst = function (validator) {
for (var i = 0; i <= this.length - 1; i++) {
if (validator(this[i])) {
return i;
}
}
return -1;
};
}

Categories