How can I add condition when pickdate called? - javascript

My html like this :
<input id="appdate" type="text" class="required" placeholder="Select Date">
My javascript like this :
...
$(document).ready(function () {
...
$('#appdate').change(function () {
console.log('when the retrieveSchedule function is called, this is not executed')
var date = $('#appdate').val();
...
});
});
appointment = function () {
function retrieveSchedule({ id, url }) {
...
$.ajax({
url: url,
type: 'GET',
data: '',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
...
var $input = $('#appdate').pickadate({
disable: _disableDate,
formatSubmit: 'yyyy-mm-dd',
min: someDate,
max: new Date((someDate.getFullYear() + 1), (someDate.getMonth() - 1), someDate.getDate()),
selectMonths: true,
selectYears: true,
close: 'Ok',
autoClose: false,
closeOnSelect: false, // Close upon selecting a date,
onClose: function () { $('.picker__input').removeClass('picker__input--target'); $('.picker').blur(); },
onRender: function () {
$('#appdate_root .picker__day-display').append('<div class="cal-notif"></div>');
var loadingcal = '<div class="cal-loading preloader-background">' +
'<div class="preloader-wrapper big active center">' +
'<div class="spinner-layer spinner-blue-only">' +
'<div class="circle-clipper left">' +
'<div class="circle"></div>' +
'</div>' +
'<div class="gap-patch">' +
'<div class="circle"></div>' +
'</div>' +
'<div class="circle-clipper right">' +
'<div class="circle"></div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
$('#appdate_root .picker__calendar-container').append(loadingcal);
}
});
// Use the picker object directly.
var picker = $input.pickadate('picker');
picker.clear();
if (picker.get('start')) {
var getdisable = picker.get('disable');
picker.set('enable', [1, 2, 3, 4, 5, 6, 7]);
picker.set('disable', _disableDate);
getdisable = picker.get('disable');
picker.render();
} else { console.log('false picker'); }
},
error: function (result) {
...
}
}).done(function () {
...
});
}
return { retrieveSchedule: retrieveSchedule }
}();
I don't display all my scripts. I only show the details of the problem I am having
When the above js file is run, it will first call the retrieveSchedule function. If ajax is successful, it will create a pickdate and display it in the input text with id = appdate
My problem is that when pickdate is successfully displayed in the input text with id = appdate, it also runs this script in $('#appdate').change(function({. I want the statement inside $('#appdate').change(function({ is not run. So it only runs when selecting pickdate. Not display pickdate
How do I make the conditions?

How about create checking variable like this
var appdateCreated = false;
$('#appdate').change(function () {
if(appdateCreated) {
console.log('when the retrieveSchedule function is called, this is not executed')
} else {
appdateCreated = true
}
});

Related

How to take JavaScript url link to my index.php page

var feedback = function (res) {
if (res.success === true) {
var get_link = res.data.link.replace(/^http:\/\//i, 'https://');
document.querySelector('.status').classList.add('bg-success');
document.querySelector('.status').innerHTML =
'Image : ' + '<br><input class="image-url" value=\"' + get_link + '\"/>' + '<img class="img" alt="Imgur-Upload" src=\"' + get_link + '\"/>';
}
};
The second portion is:
new Imgur({
clientid: '3527680b6690575', //You can change this ClientID
callback: feedback
});
How to get_link to php variable in a index.php page?
The solution is like this:
function notifvanish() {
var data = 0;
var dataset = 'set=' + data;
$.ajax({
type: "POST",
url: "notifvanish.php",
data: dataset,
cache: false,
success: function (html) {
//alert("Success");
}
});
}

ESRI WAB custom widget popup disappears after 1 second

I am working on an in-panel custom widget for our WebApp on ESRI. When the widget is active the map is listening to mouse click events. When fired, a REST service is called via ajax and the result will be displayed in a popup.
If there is no other layer like WMS/WFS active everything is working fine. But with another active layer, the popup appears for a second and then disappears.
Any idea?
define(['dojo/_base/declare', 'jimu/BaseWidget', 'esri/layers/layer', 'dojo/dom-construct', 'esri/geometry/webMercatorUtils', 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'],
function(declare, BaseWidget, Layer, domConstruct, webMercatorUtils) {
var map;
return declare([BaseWidget], {
baseClass: 'jimu-widget-myTest',
name: 'myTest',
customPopup: new Popup({
offsetX: 10,
offsetY: 10,
visibleWhenEmpty: true
},domConstruct.create("div")),
startup: function() {
map = this.map;
this.map._mapParams.infoWindow = this._customPopup;
},
onOpen: function(){
document.getElementById(this.map.id).addEventListener("click", myClickListener);
},
onClose: function(){
document.getElementById(this.map.id).removeEventListener("click", myClickListener);
}
});
function myClickListener(evt) {
if(evt.mapPoint) {
var content = "";
var mp = webMercatorUtils.webMercatorToGeographic(evt.mapPoint);
lon = mp.x;
lat = mp.y;
var service_url = "xxxxxx";
$.ajax({
method: 'GET',
url: service_url,
dataType: 'json',
error: function() {
console.log("Could not load data.");
},
success: function(result) {
for(var i = 0; i < result.values.length; i++) {
content += "<div class='test'>";
content += "<table style='width:100%'><tr><td><b>bli</b></td><td>" + result.values[i].bli + "</td></tr>" +
"<tr><td><b>bla</b></td><td>" + result.values[i].bla + "</td></tr>" +
"<tr><td><b>blub</b></td><td>" + result.values[i].blub + "</td></tr>";
content += "</table></div>";
}
map.infoWindow.setTitle("myTest");
map.infoWindow.setContent(content);
map.infoWindow.show(evt.screenPoint);
}
});
}
}
});
Problem solved by adding the Listener this way
onOpen: function(){
map.on("click", myClickListener);
},
and not like this
onOpen: function(){
document.getElementById(this.map.id).addEventListener("click", myClickListener);
},

Aurelia Select2, load remote data not loading next page

I'm trying to use Select2 and load remote data (ajax) in Aurelia. So I create a custom attribute called Select2 and follow the options in the documentation.
But, I faced an issue when I scroll to the end of the drop down a "loading more results" message appears but doesn't load more data or call the API (using the same API in the Select2 documentation to make sure I'm not missing anything).
import { customAttribute, inject , bindable, bindingMode} from 'aurelia-framework';
import 'jquery';
import 'select2';
#customAttribute('select2')
#inject(Element)
export class Select2CustomAttribute {
element;
constructor(element) {
this.element = element;
}
attached() {
var self=this;
$(this.element).select2(
{
// closeOnSelect: false,
allowClear: true,
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength:0,
templateResult: function( repo )
{
if (repo.loading) return repo.text;
var markup = "<div class='select2-result-repository clearfix'>" +
"<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' /></div>" +
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title'>" + repo.full_name + "</div>";
if (repo.description) {
markup += "<div class='select2-result-repository__description'>" + repo.description + "</div>";
}
markup += "<div class='select2-result-repository__statistics'>" +
"<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> " + repo.forks_count + " Forks</div>" +
"<div class='select2-result-repository__stargazers'><i class='fa fa-star'></i> " + repo.stargazers_count + " Stars</div>" +
"<div class='select2-result-repository__watchers'><i class='fa fa-eye'></i> " + repo.watchers_count + " Watchers</div>" +
"</div>" +
"</div></div>";
return markup;
},
templateSelection: function (repo) { return repo.full_name || repo.text; } ,
}
).on('change', evt => {
if (!evt.originalEvent) {
try{
this.element.dispatchEvent(new Event('change'));
}catch(e){
// IE 11+
try{
let evt = document.createEvent('HTMLEvents');
evt.initEvent('change', false, true);
this.element.dispatchEvent(evt);
}catch(e){
console.log(e);
}
}
}
});
}
}
I copied your code in to a gist.run and it worked fine: https://gist.run/?id=5b560eac6deff0f1b0896c30a3f12f79
The only difference is I'm loading jQuery and select2 from a CDN and not from the bundle. You can see a GIF of it working for me here: http://imgur.com/a/6uSs6

check if image exists or not and build string

I'm trying to build a string depending on an image whether it exists or not, if it exists then build an image tag if it doesn't then create an empty div tag with a class .no-image how can I accomplish this - could some give me some help
$('#search_movies').select2({
ajax: {
url: "http://localhost:8000/admin/tmdb/search",
dataType: 'json',
delay: 250,
type: 'POST',
results: function (data, page) {
console.log(data);
return { results: data.d };
},
data: function (params) {
return {
q: params.term, // search term
// page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
//params.page = params.page || 1;
console.log(data)
return {
results: data.items,
// pagination: {
// more: (params.page * 30) < data.total_count
// }
};
},
cache: false
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
function formatRepo(repo) {
if (repo.loading) return repo.text;
var markup = '<div data-id="' + repo.id + '" class="option clearfix">';
markup += '<div class="option-image"><img alt="" src="' + repo.image + '"></div>';
markup += '<div class="option-content">';
markup += '<h4>' + repo.title + '</h4>';
markup += '<h4>' + repo.release_date + '</h4>';
markup += '<h4>' + repo.popularity + '</h4>';
markup += '</div>';
markup += '</div>';
return markup;
}
function formatRepoSelection (repo) {
return repo.title || repo.text;
}
Instead of making formatRepo return the markup, make it pass the markup to a callback function like.
function formatRepo(repo, markupCallback) {
function imageExists(url, callback) {
var img = new Image();
img.onload = function() { callback(true); };
img.onerror = function() { callback(false); };
img.src = url;
}
imageExists(repo.image, function(exists) {
var markup = '';
if(exists) {
markup += '<img src="' + repo.image + '">';
} else {
markup += '<div class="no-image"></div>';
}
// pass markup to markupCallback
markupCallback(markup);
});
}
// and then use it like
formatRepo(myRepo, function(markup){
// use markup here
});

(window).scrollTop function doesn't fire at first click

I have a bar chart which is clickable, and when its clicked, it fires mainQuestBarClick function. In this function, I have this line $(window).scrollTop($('#scrollHere').offset().top); to scroll to scrollHere div. When I click to the bar, it doesn't scroll there but at second time I click it, it scrolls. What could be the reason?
Here is the function:
var mainQuestBarClick = function (event, pos, obj) {
if (!obj)
return;
$(window).scrollTop($('#scrollHere').offset().top);
//goToByScroll($("#scrollHere").attr("id"));
var selectedBranchName = encodeURIComponent(obj.series.label);
$("#SelectedBranchFromBarChart").val(selectedBranchName);
$("#content").block();
//Stats Chart
$.ajax({
type: "GET",
url: '#Url.Action("GetStatsForSpecificBranch", "SurveyReports")',
data: "BranchName="+encodeURIComponent(obj.series.label)+"&SurveyId=" + $("#SurveyId").val() + "&startDate=" + $("#ReportStartDate").val() + "&endDate=" + $("#ReportEndDate").val(),
cache: false,
success: function (r) {
if (r.success == false) {
noty({ text: r.resultText, type: 'error', timeout: 2000, modal: true });
} else {
$("#statboxSurveyCountTitle").html("<b>" + selectedBranchName + "</b> Şubesi Anket Sayısı");
$("#statboxSurveyAvgTitle").html("<b>" + selectedBranchName + "</b> Şubesi Anket Ortalaması");
$("#statboxSurveyRecommTitle").html("<b>" + selectedBranchName + "</b> Şubesi Tavsiye Oranı")
$("#StatboxesDiv").show();
$("#SurveyCountVal").text(r.FilledSurveyCount);
$("#SurveyAvgVal").text(r.FilledSurveyAverageRating.toFixed(2));
$("#SurveyRecommVal").text("%"+r.RecommendYesPercent);
}
},
error: function (error) {
noty({ text: "Bir hata oluştu lütfen tekrar deneyiniz!", type: 'error', timeout: 2000, modal: true });
}
});
$("#content").unblock();
}
This is a late solution to this problem but somehow I managed to do what I want to do. Here is how I solved the problem:
I created a function which takes the id of the element to be scrolled:
function goToByScroll(id){
#{int scroll = 600;
if(Model.BranchList.Count <= 1)
{
scroll = 750;
}
}
// Scroll
$('html,body').animate({scrollTop:#scroll}, 1000);
}
And changed this part in my code above in the question:
$(window).scrollTop($('#scrollHere').offset().top);
to this:
goToByScroll($("#scrollHere").attr("id"));

Categories

Resources