j-query date-picker does not work after post back - asp.net

I have a j-query date-picker that does not work after the first post back. It only works before the post back but the date-picker does not work after post back. the text-box that shows the date-picker is wrapped with ajax update panel. here is my j-query:
<script type="text/javascript">
$().ready(function () {
$('.date-picker').mousedown(function () {
$('.date-picker').datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy',
onClose: function (dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
}
});
});
});
</script>
<style type="text/css">
.ui-datepicker-calendar {
display: none;
}
</style>

Your issue is that on a partial post back, which is what happens when an UpdatePanel causes a post back, the DOM is not reloaded and thus your $().ready(function () { will not fire and wire up the date picker. This is one of those ASP.NET AJAX gotchas.
One way to deal with this is to have a JavaScript function invoked when the PageRequestManager does the partial post back via the UpdatePanel, like this:
<script type="text/javascript">
$().ready(function () {
$('.date-picker').mousedown(function () {
$('.date-picker').datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy',
onClose: function (dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
}
});
});
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
// Re-bind your jQuery objects here
});
</script>
Note: This is one of those places where jQuery and ASP.NET AJAX do not play nice without a little tweaking.

You should use a rebind for every page load like this :
function pageLoad() {
$('#mydatepick').unbind();
$('#mydatepick').datepicker();
};

Related

WordPress with select2 and Toastr get previous selected value destroys select2 behavior

I am using WordPress and I have used Select2 and Toastr libraries successfully.
Basically I have a dropdown and if I change, Toastr will ask whether I need to update or not.
If I click on "Yes" then it will update and if I click on "No" then my dropdown should set previous value and nothing will happen.
Currently its selecting previous value but then if I open the same dropdown try to click on it to search then its saying "The results could not be loaded".
Here is my JS code what I have done so far.
var prevSubVarClientId;
jQuery('.mySubscription').select2({
allowClear: true,
placeholder: "",
//minimumInputLength: 3,
ajax: {
type: "POST",
url: '/wp-admin/admin-ajax.php',
dataType: 'json',
delay: 250, // delay in ms while typing when to perform a AJAX search
data: function (params, page) {
return {
action: 'list_posts',
q: params.term,
};
},
processResults: function( data ) {
var options = [];
if ( data ) {
jQuery.each( data, function( index, text ) {
options.push( { id: text['id'], text: text['name'] } );
});
}
return {
results: options
};
},
cache: true
}
});
jQuery('.mySubscription').on('select2:selecting', function (evt) {
prevSubVarClientId = jQuery('select').val();
});
jQuery('.mySubscription').change(function() {
var $this = jQuery(this);
jQuery(this).blur();
alertify.confirm("Are you sure you want to transfer?",
function(e){
var subscriptionId = jQuery($this).data("subscription-id");
var url = jQuery($this).data("ajax-url");
var userId = jQuery($this).val();
jQuery.ajax({
type: "POST",
url: url,
data : {
action : 'update_var_client_user_id',
userId : userId,
subscriptionId : subscriptionId
},
success: function(data)
{
var data = JSON.parse(data);
toastr["success"]("Transferred Successfully." );
}
});
},
function(){
jQuery($this).val(prevSubVarClientId);
jQuery($this).select2().trigger('change');
}).set({title:"Alert!!!"}).set({ labels:{ok:'Yes', cancel: 'No'} });
});
As you can see I have prevSubVarClientId variable and mySubscription dropdown with this class.
jQuery('.mySubscription').change(function() { here you can see I am opening alertify confirm box and if I click on "No" then I am doing below code.
jQuery($this).val(prevSubVarClientId);
jQuery($this).select2().trigger('change');
But then whenever I am trying to open the dropdown again, I am getting the below error.
Can some one guide me, what I am doing wrong here ?
Thanks
"The results could not be loaded". only show when return data is null or not found.
I tested your code below snippet and working fine.
$(".js-data-example-ajax").select2();
jQuery('.js-data-example-ajax').on('select2:selecting', function (evt) {
prevSubVarClientId = jQuery('select').val();
});
jQuery('.js-data-example-ajax').change(function() {
var $this = jQuery(this);
jQuery(this).blur();
alertify.confirm("Are you sure you want to transfer?",
function(e){
console.log('change');
},function(){
console.log('no change');
jQuery($this).val(prevSubVarClientId);
jQuery($this).select2().trigger('change');
}).set({title:"Alert!!!"}).set({ labels:{ok:'Yes', cancel: 'No'} });
});
.select2-container, .select2-container--open .select2-dropdown--below {
width: 200px !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/css/alertify.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/alertify.min.js"></script>
<select class="js-data-example-ajax">
<option value="abc">ABC</option>
<option value="bca" selected>BCA</option>
<option value="mnp">MNP</option>
<option value="pqr">PQR</option>
</select>

FullCalender.js onclick event not working after view changed

I have added onclick event on the Fullcalender.js on the events. But when I am changing the calender view from Month to Week or Day that onclick event is not working anymore. Please help me how to fix this.
Here is my code for the first time after the page load, it working perfectly but after the change of view the click is not working:
<script>
$(document).ready(function () {
debugger;
$.ajax({
url: "/Appointment/GetAgendaList",
data: {userid:#Convert.ToInt32(Session["UserID"])},
dataType: "json",
type: "POST",
success: function (response) {
debugger;
//load all events
LoadEvents(response);
}
});
//Add click events on each Event link to get details
var clicks = 0;
$('td.fc-event-container a').on({
click: function (event) {
node = $(this);
clicks++;
if (clicks == 1) {
setTimeout(function () {
if (clicks == 1) {
$('#loderdiv').show();
var loadurl = $('input#hdneventdetailsurl').val();
var eventid = $(node).find('input.hdneve_id').val();
loadurl = loadurl + "/" + eventid;
$('#myagenda').load(loadurl, function () {
$('div#myagenda').modal('show');
$('#loderdiv').hide();
});
}
clicks = 0;
}, 300);
}
}
});
});
//Initialize the calender and add all events
function LoadEvents(data)
{
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '#DateTime.Now.ToString("yyyy-MM-dd")',
editable: true,
eventLimit: true, // allow "more" link when too many events
events:data
});
}

Jquery slider. On Slider Stop raise server side event

i would like to raise a server side event at the mouseup event of the jquery slider.
How can i accomplish this? Can you point me a good place to start?
The server side code i would like to call is
Private Sub LoadBlock(ByVal AA As Integer)
'A lot of stuff here
End Sub
The value gathered from the Jquery slider event should be passed as a parameter in the procedure above
My current JQuery is
<script type="text/javascript">
$(document).ready(function () {
var Country = ['<% =String.Join("', '", arrayString)%>'];
$('#slider-range-max').slider({
max: '<%= arrayLength%>',
min: 0,
value: '<%= iValue%>',
slide: function (event, ui) {
var splitValues = Country[ui.value].split("~");
$('#lblGame').html(splitValues[0]);
$('#hpHome').html(splitValues[1]);
},
stop: function (event, ui) { }
});
});
</script>
Finally this is not a homework!!!
<script type="text/javascript">
$(document).ready(function () {
var Country = ['<% =String.Join("', '", arrayString)%>'];
$('#slider-range-max').slider({
max: '<%= arrayLength%>',
min: 0,
value: '<%= iValue%>',
slide: function (event, ui) {
var splitValues = Country[ui.value].split("~");
$('#lblGame').html(splitValues[0]);
$('#hpHome').html(splitValues[1]);
},
stop: function (event, ui) {
//bof:AJAX hit
var path="YourPageName.aspx/NewMethod";
$.ajax({
url:path,type:"POST",cache:"false",
dataType:"json",contentType:"application/json; charset=utf-8",
data:"{'str1':'Some Temp String'}",
success:function(response){alert("response is "+response.d);
},error:function(){
}
});
//eof:AJAX hit
}
});
});
</script>
and in code behind:
<System.Web.Services.WebMethod> _
Public Shared Function NewMethod(str1 As String) As String
'make same name of variable as in json data
'do your server side stuff
Return "Success"
End Function
I don't have tested this code but certainly this will help you
take one button
<asp:Button ID="img_update" runat="server" Text="Submit" style='display:none' OnClick="img_update_Click" />
your method non-static method
protected void img_update_Click(object sender, EventArgs e)
{
//your code -behind
}
Now your jquery will looks like
<script type="text/javascript">
$(document).ready(function () {
var Country = ['<% =String.Join("', '", arrayString)%>'];
$('#slider-range-max').slider({
max: '<%= arrayLength%>',
min: 0,
value: '<%= iValue%>',
slide: function (event, ui) {
var splitValues = Country[ui.value].split("~");
$('#lblGame').html(splitValues[0]);
$('#hpHome').html(splitValues[1]);
},
stop: function (event, ui) {
document.getElementById('client id of button').click();
}
});
});
</script>
I hope this will give you better idea how to implement non-static method regards.....:)

What is the reason behind popup opening only first time

I have a strange problem and i m not able to understand why it is happening.
I called a page - Remarks(say) by jquery ajax on row click of grid viw. Then i binded that page (coming in response) into a div - dvRemarks(say). This div is opening in a popup.
Pop-up window is only opening first time, which is working fine. But when i click second time, data is coming in response, But this time popup is not opening. Problem is with popup only but i don't understand why it is ?
When i again refresh the page, it again opens up Ist time only.
Below is jquery :-
jQuery(function() {
// Remarks
jQuery('#<%=dvRemarks1.ClientID %>').dialog({
autoOpen: false,
width: 600,
modal: true
});
// Remarks Link
jQuery('#lnkDialog').click(function() {
jQuery('#<%=dvRemarks1.ClientID %>').dialog('open');
return false;
});
});
Below is the function which i am calling on click :-
function Call_Ajax(id)
{
var d = new Date();
var n = d.getMilliseconds();
var parameters="id=" + id;
$.ajax({
type: "POST",
url: "Remark.aspx",
data: {id:id, n:n},
success: function(response) {
$('#<%=dvRemarks.ClientID %>').html(response);
$("#lnkDialog").click();
},
error: function() {
alert('Some problem has been occured.');
}
});
}
And below is the div - dvRemarks in which i am binding response
<div id="dvRemarks1" runat="server" style="display: none;" title="Enter Remarks">
<div id="dvRemarks" runat="server">
</div>
</div>
Thanks.
Not sure on this but give a try to below one.
jQuery(function() {
// Remarks
jQuery('#<%=dvRemarks1.ClientID %>').dialog({
autoOpen: false,
width: 600,
modal: true, //Calling destroy on close function might help
close: function() {
$(this).dialog("destroy");
}
});
// Remarks Link
jQuery('#lnkDialog').click(function() {
jQuery('#<%=dvRemarks1.ClientID %>').dialog('open');
return false;
});
});
give a try changing ajax call to
function Call_Ajax(id)
{
var d = new Date();
var n = d.getMilliseconds();
var parameters="id=" + id;
$.ajax({
type: "POST",
url: "Remark.aspx",
data: {id:id, n:n},
success: function(response) {
$('#<%=dvRemarks.ClientID %>').empty().html(response); //empty function may be of some help here
$("#lnkDialog").click();
},
error: function() {
alert('Some problem has been occured.');
}
});
}

dayClick and eventClick function not working

I have inserted some new functions in my js but dayClick and eventClick don't work. The calendar is able to load properly though.
Any idea why the dayclick and eventclick in the following code is not working?
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: '',
right: 'agendaWeek,agendaDay'
},
selectable: true,
selectHelper: true,
allDayDefault: false,
allDaySlot: false,
firstHour: 9,
defaultView: 'agendaWeek',
dayClick: function(date, allDay, jsEvent, view) {
calendar.fullCalendar('gotoDate', date);
},
eventClick: function(calEvent, jsEvent, view) {
window.location = "http://www.domain.com?start=" + calEvent.start;
},
select: function(start, end) {
var title = prompt('Event Title:');
if (title) {
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end
},
false // make the event "stick"
);
var startDateString = $.fullCalendar.formatDate(start, 'yyyy-MM-dd hh:mm');
var endDateString = $.fullCalendar.formatDate(end, 'yyyy-MM-dd hh:mm');
$.ajax({
type: 'POST',
url: '{url}ajaxpost/add',
data: {
startDate: startDateString,
endDate: endDateString,
eventTitle: title
},
dateType: 'json',
success: function (resp) {
calendar.fullCalendar('refetchEvents');
}
});
}
calendar.fullCalendar('unselect');
},
editable: true,
events: "{url}ajaxget/data",
});
});
You cannot use the "select" callback and the "dayClick" callback together as there is a conflict between the two. You can use datepicker to accomplish the gotoDate function to accomplish the same thing.
http://weblogs.asp.net/gunnarpeipman/archive/2010/02/02/linking-jqueryui-datepicker-and-fullcalendar.aspx
As for the eventClick Im not sure why it is not working, but it is easier to place the url in the database the call it in the events and just set it as the property "url: www.somesite.com/sdfjkiwe"
As a side note, It would probably wor better if you didn't use renderEvent to display your event. Try using the event function found here to use your ajax call within it.
http://arshaw.com/fullcalendar/docs/event_data/events_function/

Resources