Function triggering before I select a date in datepicker - javascript

I need the help of the experts on here.
When I call the function v9_insert_comments('1') the alert(sdate) triggers before I even get to select a date in the datepicker.
My goal is to have the v9_insert_comments() check to see if the sdate is null or not. If its null then just { return } if not { do something else }.
The current case if that sdate is always null because the datepicker never gets a chance to set it.
var sdate
//========================================================================
function v9_insert_comments(x) {
//========================================================================
if (x == 1) {
select_date()
alert(sdate)
}
}//end of function
//========================================================================
function select_date() {
//========================================================================
$('#dd').dialog({
autoOpen: true,
modal: true,
overlay: {
opacity: 0.5,
background: 'black'
},
title: "title",
height: 265,
width: 235,
draggable: false,
resizable: false
}); //end of dialog
$('#d1').datepicker({
onSelect: function() {
sdate = $(this).val();
$("#dd").dialog("close");
}
});
} //end of function
Body:
<!-- START OF DATE SELECTOR DIALOG -->
<div style="display:none" id="dd">
<div id="d1"></div>
</div>
<!-- END OF DATE SELECTOR DIALOG -->

In your select_date method you're just setting stuff up. The call to $('#dd').dialog() does all the jQuery UI magic to create a dialog, by updating the DOM and wiring things up. Then you call $('#d1').datepicker(), which sets up a datepicker in a similar way. It's just saying "this div is now a dialog, and this div is now a datepicker". It's not waiting for any user interaction. Your v9_insert_comments function is assuming things are happening synchronously, whereas they're actually happening asynchronously.
After these things are set up, you immediately ask for the value of a variable that hasn't been set yet. It hasn't been set because the anonymous function you supplied for the datepicker's onSelect event hasn't fired yet. This function will only be called when something has been selected in the datepicker. So if you want to do something with the selected date, do it in the event handler.
You could move your alert to the event handler, or you could call v9_insert_comments from the event handler - but in this case you should move the call to select_date elsewhere. The dialog and datepicker only need to be set up once.

Related

Reset idleTimeout counter between ajax post

I am using JQuery idleTimeout plugin from here :
http://www.erichynds.com/examples/jquery-idle-timeout/example-mint.htm
I'm using it in an mvc 4 application.
Below is the code snippet where i set the session timer.
<script type="text/javascript">
var sessionTimer = 60;
$(document).ready(function ()
{
// setup the dialog
$("#dialog").dialog({
autoOpen: false,
modal: true,
width: 400,
height: 210,
closeOnEscape: false,
draggable: false,
resizable: false,
buttons: {
'Yes, Keep Working': function () {
$(this).dialog('close');
},
'No, Logoff': function () {
// fire whatever the configured onTimeout callback is.
// using .call(this) keeps the default behavior of "this" being the warning
// element (the dialog in this case) inside the callback.
$.idleTimeout.options.onTimeout.call(this);
}
}
});
var $countdown = $("#dialog-countdown");
#* start the idle timer plugin *#
$.idleTimeout('#dialog', '#dialog-button-yes', {
idleAfter: (sessionTimer - 30),
keepAliveURL: '#Url.Action("KeepAlive", "Home")',
pollingInterval: 5,
serverResponseEquals: 'OK',
AJAXTimeout: 250 * 60,
onTimeout: function () {
window.location = '#Url.Action("Logout", "Login")';
},
onIdle: function () {
$(this).dialog("open");
},
onCountdown: function (counter) {
$countdown.html(counter); #* update the counter *#
}
});
});
This code is placed in the outermost/shared view. All my pages are loaded using partial views using jquery $.ajax. The above code is loaded only once, the sessionTimer gets set to 60 seconds. So the timer does not resets when a new page gets loaded calling ajax post. Even though the user is active, the timer is ticking between the posts.
Is there a way for me to reset the counter every time an ajax post takes place.
I can reset this on every inner views $.ajax success condition. But there are too many places. I would like to know if there is a common code I can write on this master page of mine, that will let me know that an ajax call has been placed and to reset the counter.
Try using the .ajaxSuccess() event handler from jQuery. You can check the documentation on how to use it here: http://api.jquery.com/ajaxsuccess/ .

jQuery always prevents the action of the first click

I have several "Purchase Now" buttons of different articles. When the button has the class "sold-out" it shouldn't do anything otherwise it should open a jQuery Magnific Popup. So far that works. My problem is, that when I click for the first time I visit the homepage the purchaseable "Purchase Now" button, it isn't doing anything. When I click for the second time on it, it opens the jQuery window. But why it doesn't work for the first time already ??
My HTML:
Purchase Now
My JQuery:
$('.open-popup-link').magnificPopup({
type:'inline',
midClick: true,
mainClass: 'mfp-fade'
});
$('.ajax-popup').click(function(e){
e.preventDefault();
if($(this).hasClass("sold-out")) {
return false;
}
var region = $(this).data('region');
var quantity = $(this).data('quantity');
if(typeof quantity == 'undefined') quantity = $(this).parent().find('select').val();
var packageid = $(this).data('packageid');
$(this).magnificPopup({
type: 'ajax',
ajax: {
settings: {
data : {
region : region,
quantity : quantity,
packageid : packageid,
}
}
},
closeOnContentClick: false,
closeOnBgClick: false
});
});
It might be because you are declaring the popup definition within the click function. Can you try declaring the function outside the click function?
It doesn't open on first click cause this is the time you BIND it to the element.
Hovewer, we see in documentation that we can instantly open MagnificPopup.
// Open popup immediately. If popup is already opened - it'll just overwite the content (but old options will be kept).
// - first parameter: options object
// - second parameter (optional): index of item to open
$.magnificPopup.open({
items: {
src: 'someimage.jpg'
},
type: 'image'
// You may add options here, they're exactly the same as for $.fn.magnificPopup call
// Note that some settings that rely on click event (like disableOn or midClick) will not work here
}, 0);
http://dimsemenov.com/plugins/magnific-popup/documentation.html#options

jQuery UI dialog title task

How would you override jQuery UI's default functionality so that whenever I set a new title for a dialog - it adds xxx in front of it? So $("#any_dialog_id").dialog("option", "title", "yyy") would set title to xxxyyy.
$().ready(function(){
$("#dialog").dialog();
$(".ui-dialog-title").before("xxx");
// I add the line //
$("#any_dialog_id").dialog("option", "title", "yyy");
});
But he show yyyxxx not xxxyyy
What I have to do, to make it work??
Thanks...
There are many ways you could do this.
The very simplest is to run your line $(".ui-dialog-title").before("xxx"); AFTER each call to opening a dialog. You cannot merely run it once and expect it to re-run on later dialog calls.
Another way to do this is to modify the jquery code. But I HIGHLY disrecommend doing that.
If I were to really want to systematically apply a prefix, I would make a helper function or wrapper that do this for me and call it instead of the jquery dialog directly.
Here is an example of what you might do and I have included a jsfiddle link as well (http://jsfiddle.net/stdw6j5q/1/):
HTML:
<div id="idDiv_MyDialog">Hi 1!</div>
<div id="idDiv_MyDialog2">Hi 2!</div>
<div id="idDiv_MyDialog3">Hi 3!</div>
<div id="idDiv_MyDialog4">Hi 4!</div>
JAVASCRIPT:
jDialog = function(options) {
// THE WRAPPER TAKES TWO EXTRA OPTIONS TO IDENTIFY THE DIALOG AND THE TITLE PREFIX TO USE
// I SET A DEFAULT SELECTOR IF NOTHING IS PASSED IN
var _dialog = options && options.dialog ? options.dialog : '#idDiv_MyDialog';
// HERE YOU CAN SET A DEFAULT PREFIX
var _titlePrefix = options && options.titlePrefix ? options.titlePrefix : 'XYZ: ';
// UPDATE THE TITLE OPTION
options.title = _titlePrefix + options.title;
// PASS THROUGH ALL YOUR NORMAL OPTIONS TO THE DIALOG
$(_dialog).dialog(options);
// THIS RETURNS A HANDLE/REFERENCE TO THE DIALOG CREATED
return $(_dialog);
}
$(function() {
// CALL YOUR WRAPPER WHEN YOU NEED TO CREATE/MOD THE DIALOG
$myDialog1 = jDialog({
title: 'Hey Jude',
close: function(event, ui) { $myDialog2.dialog('open'); }
});
$myDialog2 = jDialog({
dialog: '#idDiv_MyDialog2',
title: 'Don\'t let me down',
autoOpen: false,
close: function(event, ui) { $myDialog3.dialog('open'); }
});
$myDialog3 = jDialog({
dialog: '#idDiv_MyDialog3',
title: 'Take a sad song',
autoOpen: false,
close: function(event, ui) { $myDialog4dialog('open'); }
});
$myDialog4 = jDialog({
dialog: '#idDiv_MyDialog4',
title: 'And make it better',
autoOpen: false
});
});
You can set an event to run whenever a dialog is created that adds the title.
$(document).on('dialogcreate', function(){ // let it bubble up
$(".ui-dialog-title", this).before("xxx"); // add "xxx" before the title of this dialog
});

How do I hide a jquery dialog until content is retrieved?

I have a button's onclick set to use the following function EditContact. This function sets up a jquery dialog, gets the data from the server and displays it. Everything works but I would like to get it to work a little better. Right now the empty dialog pops up for the time it takes the code to go and fetch the content from the server then the dialog populates with the content. My question is how can I get the dialog to not pop up until the content has been received.
function EditContact() {
$('#editContactView').dialog({
modal: true,
width: 'auto',
position: ['top', 'center'],
resizable: false,
autoOpen: false,
open: function (event) {
var szAction = "Content url for this example";
$(this).load(szAction,
function (response, status, xhr) {
$('#editContactView').dialog('open');
return false;
});
}
});
$('#editContactView').dialog('open');
}
I think you should be able to essentially turn what you have inside out and and open the dialog on $().load() completion. Something like this might do it:
function editContact() {
var szAction = "Content url for this example";
$(this).load(szAction, function (response, status, xhr) {
$('#editContactView').dialog({
modal: true,
width: 'auto',
position: ['top', 'center'],
resizable: false
});
});
}
Edit:
Notice I removed the {autoOpen: false}. This will create it and open it in one shot after you receive the content.
You are calling .dialog('open') twice: in the end of the code and in the callback for the loading.
As JavaScript is asynchronous, it runs the line $('#editContactView').dialog('open'); in the end before the data is received.
Removing this line should solve the problem.

Inheritance causes function to be executed so many times Javascript

I am learning JavaScript and I got stuck creating a function to minimize a window. The problem is that this functions seems to stack in itself so many times.
Gere is my principal function :
function displayChatWindow(user, status, avatar, id){
var template = _.template($("#windowTemplate").html(), {userName: user, userStatus: status, userAvatar: avatar, userId: id});
stackingWidth = stackingWidth - boxWidth;
console.log(stackingWidth);
$("body").prepend(template);
$(".messages-container").slimScroll({
height: '200',
size: '10px',
position: 'right',
color: '#535a61',
alwaysVisible: false,
distance: '0',
railVisible: true,
railColor: '#222',
railOpacity: 0.3,
wheelStep: 10,
disableFadeOut: false,
start: "bottom"
});
$("#" + id).css({
top: absoluteY,
left: stackingWidth
});
$(".minimize-others").on("click", displayOthersChat);
$(".chat input, .chat textarea").on("focus", cleanInputs);
$(".chat input, .chat textarea").on("blur", setInputs);
}
This function receives some parameters and with a template creates the chat window. At the end it applies the function to minimize the window (displayOthersChat) and load plugins and stuff for each window.
My displayOtherChats function:
function displayOthersChat(e){
/*e.preventDefault();*/
var This = $(this).parent().parent();
var minimize = This;
if(!This.hasClass("draggable")){
This.animate({
top: windowHeight - boxHeight - 20
});
This.addClass("draggable");
This.draggable({handle: ".header"});
var timeOut = setTimeout(function() {
This.find(".minimize").toggleClass("rotate");
}, 500);
}else{
This.draggable("destroy");
This.removeClass("draggable");
var timeOut = setTimeout(function() {
This.find(".minimize").toggleClass("rotate");
}, 500);
This.animate({
top: absoluteY
});
}
/*return false;*/
}
This seems to work really well. If I open my first window it displays and also minimizing the window works. When I open another window, the last window works correctly but the first window opens when I try to minimize it.
It seems that it calls the function twice, and if I open a third window, the first window calls the function three times.
I actually don't know whats going on, I will appreciate if you guys could help me. I also leave a link so you guys can see whats going on: http://s3.enigmind.com/jgonzalez/nodeChat.
The problem seems to be that you are binding the same event handler to the same elements over and over again.
$(".minimize-others").on("click", displayOthersChat); will bind displayOthersChat to all existing elements with class minimize-others. .on always adds event handlers, it does not replace them. So if you call displayChatWindow multiple times, you are binding the event handler to the .minimize-others elements multiple times.
You only want to bind the handler to the window that was just created, for example:
// create reusable jQuery object from HTML string.
var $template = $(template).prependTo('body');
// instead of $("body").prepend(template);
// ...
$template.find('.minimize-others').on('click', displayOthersChat);
Same goes for the other event handlers.
Alternatively, you could bind the event handler once, outside of the function and use event delegation to capture the event:
$(document.body).on('click', '.minimize-others', displayOthersChat);

Categories

Resources