I wrote below function in javascript file.
Previously, below function works on my server and local, but today it works on my local only. Suddenly it stops working on server. i checked the code there is no any change. I don't understand why this happens.?
jQuery.fn.guideWidget = function(e) {
alert("guideWdget");
},
jQuery.fn.loading = function() {
this.prepend("<div class='fnLoading' style='height:" + this.height() + "px;width:" + this.width() + "px'><div class='ajaxOverlayInvis' style='display:block'></div><div class='ajaxOverlay' style='display:block;position:absolute'><div class='loadingimage' style='display:block'></div></div></div>")
},
jQuery.fn.loadingDone = function() {
this.find("div.fnLoading").first().remove()
}
Is there any alternate way to write above function?
What am i doing wrong in above function please suggest me.
Related
I have a post that work well when I run from VS2015 debug:
$("#DisplayChartType").bind("change", function () {
$.post("../Employee/ChangeDisplayChartType", { displayChartType: $("#DisplayChartType").val() }, function (data) {
iDependOnMyParameter(data);
})
});
But post does not work once I have published to IIS. I tried using ../, / and ~/ in the post but none work. I searched web and found the approach below but I still get ARG1 being sent as a parameter instead of my javascript variable.
$("#DisplayChartType").bind("change", function () {
$.post("#Html.Action("ChangeDisplayChartType", "Employee", new { displayChartType = "ARG1" })".replace("ARG1",$("#DisplayChartType").val()) , function (data) {
iDependOnMyParameter(data);
})
});
How should I do this? I really would like to stay with $.post approach as that works nicely in VS.
You can try this code.
$("#DisplayChartType").bind("change", function () {
var chartType = $("#DisplayChartType").val();
var url="#Url.Action("ChangeDisplayChartType", "Employee", new { displayChartType = "ARG1" })";
$.post(url.replace("ARG1", chartType), function (data) {
iDependOnMyParameter(data);
})
});
So add it to the url
$.post("../Employee/ChangeDisplayChartType?displayChartType=" + encodeURIComponent($("#DisplayChartType").val()), function(){});
or change your original code to GET and the value will be added to the querystring.
You can use window.location.origin or document.location.origin to get the origin of your website, whether running in VS 2015 debug or on IIS.
So instead of doing
$.post("../Employee/ChangeDisplayChartType"
You can try
$.post(document.location.origin + "/Employee/ChangeDisplayChartType"
#OJ Raqueno put me on the right path.
At top of script I now declare "myPath". My website URL ends with "secure" so this test gives me the right path:
var myPath = document.URL;
if (!myPath.endsWith("secure")) {
myPath = "";
}
Then I do this:
$("#DisplayChartType").bind("change", function () {
$.post(myPath + "/Employee/ChangeDisplayChartType", { displayChartType: $("#DisplayChartType").val() }, function (data) {
alert($("#DisplayChartType").val());
iDependOnMyParameter(data);
})
});
I need to do something when view change. For example when from motnh go to agendaDay.
Didnt work anythink.any ideas?
viewRender:(function() {
var lastViewName;
return function(view) {
var view = $('#calendar').fullCalendar('getView');
alert('The new title of the view is ' + view.title);
}
}),
and
viewRender:(function(view) {
var view = $('#calendar').fullCalendar('getView');
alert('The new title of the view is ' + view.title);
}),
In FullCalendar 5 this seems to be datesSet: https://fullcalendar.io/docs/datesSet
Small error in the code. You want the function inside the () to return another function but it isn't running. The correct form is:
(function() {
return function(){...};
})(); //extra parentheses run the function
This is called a Self-Executing Anonymous Function.
Your code works when you do:
viewRender: (function () {
var lastViewName;
return function (view) {
var view = $('#calendar').fullCalendar('getView');
alert('The new title of the view is ' + view.title);
}
})(),
Little late but try:
eventAfterAllRender: (function (view) {
// your code
}),
As noted by #Willow (thanks), accepted answer will not work in version 5x.
viewRender, eventAfterAllRender, datesRender are all obsolete and break in version 5. Below are some FullCalendar documentations I found listing breaking changes per release.
ver. 4 Upgrading from v3
ver. 5 Upgrading from v4
DatesSet is the property to be used. Screenshot from ver. 5 documentation:
Taking your code example, below works for me. In case it benefits someone else.
// version 5.11.0 based code
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
...
datesSet: function (dateInfo) {
var view = dateInfo.view;
alert('The new title of the view is ' + view.title);
},
...
});
calendar.render();
});
First Question here, too! Yay! Just moved this from AskUbuntu.
I am just about to finish a little private project for gaining some experience where i try to change the app layout so it works as a normal website (on Jimdo, so it was quite of a challenge first) without much JavaScript required but is fully functional on mobile view.
Since Jimdo serves naturally only the actual site, I had to implement an
if (activeTab.getAttribute('jimdo-target') != null)
location.href = activeTab.getAttribute('jimdo-target');
redirect into the __doSelectTab() function in tabs.js . (In js I took the values from the jimdo menu string to build the TABS menu with this link attribute)
Now everything works fine exept at page load the first tab is selected. I got it to set the .active and .inactive classes right easily, but it is not shifted to the left.
So my next idea is to let it initialize as always and then send a command to change to the current tab.
Do you have any idea how to manage this? I couldn't because of the this.thisandthat element I apparently don't really understand...
Most of you answering have the toolkit and the whole code, but I am listing the select function part of the tabs.js:
__doSelectTab: function(tabElement, forcedSelection) {
if ( ! tabElement)
return;
if (tabElement.getAttribute("data-role") !== 'tabitem')
return;
if (forcedSelection ||
(Array.prototype.slice.call(tabElement.classList)).indexOf('inactive') > -1) {
window.clearTimeout(t2);
activeTab = this._tabs.querySelector('[data-role="tabitem"].active');
offsetX = this.offsetLeft;
this._tabs.style['-webkit-transition-duration'] = '.3s';
this._tabs.style.webkitTransform = 'translate3d(-' + offsetX + 'px,0,0)';
this.__updateActiveTab(tabElement, activeTab);
if (activeTab.getAttribute('jimdo-target') != null)
location.href = activeTab.getAttribute('jimdo-target');
[].forEach.call(this._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)'), function (e) {
e.classList.remove('inactive');
});
var targetPageId = tabElement.getAttribute('data-page');
this.activate(targetPageId);
this.__dispatchTabChangedEvent(targetPageId);
} else {
[].forEach.call(this._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)'), function (el) {
el.classList.toggle('inactive');
});
var self = this;
t2 = window.setTimeout(function () {
var nonActiveTabs = self._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)');
[].forEach.call(nonActiveTabs, function (el) {
el.classList.toggle('inactive');
});
}, 3000);
}
},
...and my app.js hasn't anything special:
var UI = new UbuntuUI();
document.addEventListener('deviceready', function() { console.log('device ready') }, true);
$(document).ready(function () {
recreate_jimdo_nav();
UI.init();
});
So meanwhile found a simple workaround, however I'd still like to know if there is another way. Eventually I noticed the __doSelectTab() function is the one that executes the click, so it does nothing but to show the other tab names when they are hidden first. so I added the global value
var jnavinitialized = false;
at the beginning of the tabs.js and run
var t = this;
setTimeout(function(){t.__doSelectTab(t._tabs.querySelector('[data-role="tabitem"].jnav-current'))}, 0);
setTimeout(function(){t.__doSelectTab(t._tabs.querySelector('[data-role="tabitem"].jnav-current'))}, 1);
setTimeout(function(){jnavinitialized = true;}, 10);
at the top of the __setupInitialTabVisibility() function. Then I changed the location.href command to
if (activeTab.getAttribute('jimdo-target') != null && jnavinitialized)
location.href = activeTab.getAttribute('jimdo-target');
And it works. But originally I searched for a way to change the tab on command, not to run the command for selecting twice. So if you know a better or cleaner way, you are welcome!
I'm new to the Jquery world and am having an issue with the code below. I'm hoping you can let me know what I'm doing wrong.
<script type="text/javascript">
$(document).ready(function () {
$('#SocialSecurity').on('input', function () {
var newNum = jQuery('#SocialSecurity');
if (newNum.val().contains("x")) {
newNum.val("");
} newNum.clone().attr('alt','999-99-9999').insertAfter('#SocialSecurity').prev().remove();
$('#SocialSecurity').focus();
});
});
</script>
The issue I am having is that my application has a SSN box which on page load,for security reasons, is populated xxx-xx-9999. However, if a user wants to update it I am attempting to clone the box, but changing the format to 999-99-9999.
The code above works fine in Firefox, however in Chrome and all versions of I.E. the field is not auto-inserting the dashes for the SSN. This causes the authentication to fail.
A few changes I've tried after research that have not worked are,
Changing the attr() to prop()
Changing the $ to Javascript
I appreciate any advice you can give me. Also let me know if I need to provide any additional information/code.
Regards,
I believe this is what you are trying to do.
JSFiddle
$(document).ready(function () {
$('#SocialSecurity').on('input', function () {
var $ss = $(this);
var ssval = $ss.val();
if (ssval.indexOf("x") > -1) {
$ss.val("");
} else {
ssval = ssval.split(/\D+/g).join('');
ssvals = ssval.match(/(\d{1,3})(?:(\d{1,2})(\d{1,4})?)?/);
if (ssvals) {
ssvals.shift();
ssval = ssvals.filter(Boolean).join("-");
}
$ss.val(ssval);
}
});
});
Please try this
Demo: jsFiddle
$(document).ready(function () {
$('#SocialSecurity').on('input', function () {
var newNum = jQuery('#SocialSecurity');
if (newNum.val().indexOf("x")) {
newNum.val("");
} newNum.clone().val('999-99-9999').insertAfter('#SocialSecurity').prev().remove();
$('#SocialSecurity').focus();
});
});
We're currently not using any serious client side framework besides jQuery (and jQuery.ui + validation + form wizard plugins).
A problem that surfaces a few times in our code is this:
We have a button that initiates an Ajax call to the server.
While the call is taking place, we display a "loading" icon with some text
If the server returns a result too quickly (e.g. < 200 ms), we "sleep" for 200 millis (using setTimeout()), to prevent flickering of the waiting icon & text.
After max(the call returns, a minimal timeout), we clear the loading icon & text.
We then either display an error text, if there was some problem in the ajax call (the server doesn't return 500, but a custom json that has an "error message" property. In fact, sometimes we have such a property in the response per form field ... and we then match errors to form fields ... but I digress).
In case of success, we do ... something (depends on the situation).
I'm trying to minimize code reuse, and either write or reuse a pattern / piece of code / framework that does this. While I probably won't start using an entire new heavy-duty framework just for this use case, I would still like to know what my options are ... perhaps such a client-side framework would be good for other things as well. If there's a lightweight framework that doesn't require me to turn all my code upside down, and I could use just on specific cases, then we might actually use it instead of reinventing the wheel.
I just recently heard about Ember.js - is it a good fit for solving this problem? How would you solve it?
$(function(){
var buttonSelector = "#button";
$('body').on({'click': function(evt){
var $button = $(this);
$button.toggleClass('loading');
var time = new Date();
$.get('some/ajax').then(function(data,text,jqXhr){
// typical guess at load work
$button.empty();
$(data).wrap($button);
}).fail(function(data,text,jqXhr){
alert("failed");
}).done(function(data,text,jqXhr){
var elapsed = new Date();
if((elapsed - time) < 200){
alert("to short, wait");
}
$button.toggleClass('loading');
});
}},buttonSelector,null);
});
Just wrap the $.ajax in your own function. that way you can implement your own queing etc. I would suggest to do a jquery component for this. It can get pretty powerful, for example you can also pass http headers etc.
Regarding frameworks it depends on your requirements.
For example, you may consider Kendo UI, it has good framework for creating data sources:
http://demos.kendoui.com/web/datasource/index.html.
Working Sample Code (well, almost)
I was going for something along the lines of #DefyGravity's answer anyway - his idea is good, but is still pseudo-code/not fully complete. Here is my working code (almost working demo, up to the Ajax URL itself, and UI tweaks)
The code & usage example:
jQuery.fn.disable = function() {
$(this).attr("disabled", "disabled");
$(this).removeClass("enabled");
// Special handling of jquery-ui buttons: http://stackoverflow.com/questions/3646408/how-can-i-disable-a-button-on-a-jquery-ui-dialog
$(this).filter("button").button({disabled: true});
};
jQuery.fn.enable = function() {
$(this).removeAttr("disabled");
$(this).addClass("enabled");
// Special handling of jquery-ui buttons: http://stackoverflow.com/questions/3646408/how-can-i-disable-a-button-on-a-jquery-ui-dialog
$(this).filter("button").button({disabled: false});
};
function AjaxCallbackWaiter(ajaxUrl, button, notificationArea, loadingMessage, errorMessage, inSuccessHandler, inFailureHandler) {
// Every request that takes less than this, will be intentionally delayed to prevent a flickering effect
// http://ripper234.com/p/sometimes-a-little-sleep-is-ok/
var minimalRequestTime = 800;
var loadingIconUrl = 'http://loadinfo.net/images/preview/11_cyrcle_one_24.gif?1200916238';
var loadingImageContent = $("<img class='loading-image small' src='" + loadingIconUrl + "'/><span class='loading-text'>" + loadingMessage + "</span>");
var errorContentTemplate = $("<span class='error ajax-errors'></span>");
var requestSentTime = null;
button.click(clickHandler);
function displayLoadingMessage() {
clearNotificationArea();
notificationArea.html(loadingImageContent);
}
function clearNotificationArea() {
notificationArea.html("");
}
function displayError(message) {
var errorContent = errorContentTemplate.clone(errorContentTemplate).html(message);
notificationArea.html(errorContent);
}
function ajaxHandler(result) {
var requestReceivedTime = new Date().getTime();
var timeElapsed = requestReceivedTime - requestSentTime;
// Reset requestSentTime, preparing it for the next request
requestSentTime = null;
var sleepTime = Math.max(0, minimalRequestTime - timeElapsed);
function action() {
clearNotificationArea();
button.enable();
if (result) {
inSuccessHandler();
} else {
displayError(errorMessage);
inFailureHandler();
}
}
if (sleepTime <= 0) {
action();
} else {
setTimeout(action, sleepTime);
}
}
function failureHandler() {
}
function clickHandler(){
if (requestSentTime !== null) {
logError("Bad state, expected null");
}
requestSentTime = new Date().getTime();
displayLoadingMessage();
button.disable();
$.get(ajaxUrl, 'json').then(ajaxHandler, failureHandler);
}
}
// Usage:
var ajaxUrl = 'FILL IN YOUR OWN URL HERE';
var button = $("#clickme");
var notificationArea = $(".ajax-notification-area");
var waitingMessage = "Doing Stuff";
var errorMessage = "Not Good<br/> Please try again";
$(document).ready(function(){
new AjaxCallbackWaiter(
ajaxUrl,
button,
notificationArea,
waitingMessage,
errorMessage,
function(){
alert("All is well with the world");
},
function(){
alert("Not good - winter is coming");
});
});