Jquery Cascading Drop Down how to trigger the change event for all the dropdowns in the chain Sequencially - asp.net

I have the following jQuery code in my application that drives four cascading dropdowns. I have seen numerous examples online that force the user to select a value by adding a '--Select a Value---' option. However, what I am trying to do is, for the dropdowns, update automatically in the order if one of them changes.
update 2,3,4 if 1 changes and 3,4 if 2 changes, etc.
Dropdown1 Center Dropdown2 Geo Dropdown3 Sup Dropdown4 Emp
This is the jQuery code I have:
$(function() {
$('#divParentaccordion').accordion({ autoHeight: false }).accordion({ collapsible: true });
$('#divGenericaccordion').accordion({ autoHeight: false }).accordion({ collapsible: true });
$('#<% =ddCenter.ClientID %>').change(getGeo());
$('#<% =ddGeo.ClientID %>').change(getSup());
$('#<% =ddSup.ClientID %>').change(getEmp());
// Statements i assume should call the function when the event triggers
})
function getGeo() {
$.ajax({
type: "POST",
url: "./ObservationsReport.aspx/GetGeoList",
data: "{center: '" + $('#<% =ddCenter.ClientID %>').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var geos = typeof (response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#<% =ddGeo.ClientID %>').removeOption(/./);
for (var i = 0; i < geos.length; i++) {
var val = geos[i].Code;
var text = geos[i].Description;
$('#<% =ddGeo.ClientID %>').addOption(val, text);
}
}
})
}
function getSup() {
var center = $('#<% =ddCenter.ClientID %>').val();
var geo = $('#<% =ddGeo.ClientID %>').val();
$.ajax({
type: "POST",
url: "./ObservationsReport.aspx/GetSupList",
data: "{center:'" + center + "',geo:'" + geo + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var sups = typeof (response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#<% =ddSup.ClientID %>').removeOption(/./);
for (var i = 0; i < sups.length; i++) {
var val = sups[i].SOPId;
var text = sups[i].Name;
$('#<% =ddSup.ClientID %>').addOption(val, text);
}
}
})
}
function getEmp() {
var center = $('#<% =ddCenter.ClientID %>').val();
var geo = $('#<% =ddGeo.ClientID %>').val();
var sup = $('#<% =ddSup.ClientID %>').val();
$.ajax({
type: "POST",
url: "ObservationsReport.aspx/GetEmpList",
data: "{center:'" + center + "',geo:'" + geo + "',sup:'" + sup + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var emps = typeof (response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#<% =ddEmp.ClientID %>').removeOption(/./);
for (var i = 0; i < emps.length; i++) {
var val = emps[i].Sop_Id;
var text = emps[i].Name;
$('#<% =ddEmp.ClientID %>').addOption(val, text);
}
}
})
}
What am I doing wrong? I have recently started programming in jQuery; still not completely familiar with how it handles the events and when. Please, any help will be appreciated.

I think your issue is that you're expecting the population of a box from the ajax call to trigger that select's onchange. This is not the case. Changes through javascript do not fire onchange. You will need to fire the onchange yourself.
For example, try changing getGeo to this:
function getGeo() {
$.ajax({
type: "POST",
url: "./ObservationsReport.aspx/GetGeoList",
data: "{center: '" + $('#<% =ddCenter.ClientID %>').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var geos = typeof (response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#<% =ddGeo.ClientID %>').removeOption(/./);
for (var i = 0; i < geos.length; i++) {
var val = geos[i].Code;
var text = geos[i].Description;
$('#<% =ddGeo.ClientID %>').addOption(val, text);
}
// *** CALL getSup directly ***
getSup() ;
}
})
}
The key here is the explicit call to getSup as it will not be triggered onchange.

Related

Is there a way to disable cache on FullCalendar?

I'm using FullCalendar on asp.net application. I noticed that when FullCalendar receives data from SQL Server via Web-Method > JSON, it creates a cache file (EventList.json) inside browser history/temporary folder.
I have cache:false on every method but I don't know how to apply the same thing on events: calendar.asmx/EventList .
Please refer to my other post that shows how I receive my data via web-method.
So my questions are:
Is there a way to disable cache on events?
How can I use ajax like other methods to get data, because with this method I can disable cache
function runCalendar() {
var $modal = $('#event-modal');
$('#external-events div.external-event').each(function() {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim($(this).text()) // use the element's text as the event title
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
/* Initialize the calendar */
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var form = '';
var today = new Date($.now());
var calendar = $('#calendar').fullCalendar({
slotDuration: '00:15:00',
/* If we want to split day time each 15minutes */
minTime: '08:00:00',
maxTime: '20:00:00',
timeFormat: 'HH(:mm)',
defaultView: 'agendaWeek',
events: "calendar.asmx/EventList",
lazyFetching: false,
allDaySlot: false,
firstDay: 1,
//weekends: false,
handleWindowResize: true,
//columnFormat:'ddd / DD',
selectHelper: true,
height: $(window).height() - 200,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
droppable: true, // this allows things to be dropped onto the calendar !!!
eventLimit: true, // allow "more" link when too many events
drop: function(date) {
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
var $categoryClass = $(this).attr('data-class');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
if ($categoryClass) copiedEventObject['className'] = [$categoryClass];
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
if ($('#drop-remove').is(':checked')) {
// if so, remove the element from the "Draggable Events" list
$(this).remove();
}
},
selectable: true,
eventClick: function(calEvent, jsEvent, view) {
var form = $("<form></form>");
form.append("<label>Change event name</label>");
form.append("<div class='input-group'><input class='form-control' type=text value='" + calEvent.title + "' /><span class='input-group-btn'><button type='submit' class='btn btn-success'><i class='fa fa-check'></i> Save</button></span></div>");
$modal.modal({
backdrop: 'static'
});
$modal.find('.delete-event').show().end().find('.save-event').hide().end().find('.modal-body').empty().prepend(form).end().find('.delete-event').unbind('click').click(function() {
calendar.fullCalendar('removeEvents', function(ev) {
$.ajax({
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/DeleteCalendarEvent",
dataType: "json",
data: "{'id':'" + calEvent._id + "'}",
});
return (ev._id == calEvent._id);
});
$modal.modal('hide');
});
$modal.find('form').on('submit', function() {
calEvent.title = form.find("input[type=text]").val();
calendar.fullCalendar('updateEvent', calEvent);
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/UpdateCalendarEvent",
dataType: "json",
data: "{'id':'" + calEvent._id + "','title':'" + calEvent.title + "'}",
});
$modal.modal('hide');
return false;
});
},
eventDrop: function(event, ui, jsEvent) {
$.ajax({
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/MoveEvents",
dataType: "json",
data: "{'id':'" + event._id + "','start':'" + moment(event.start).format("DD MMMM YYYY HH:mm:ss") + "','end':'" + moment(event.end).format("DD MMMM YYYY HH:mm:ss") + "','allDay':'" + event.allDay + "'}",
});
},
eventResize: function(event, allDay) {
var allDay = !event.start.hasTime() && !event.end.hasTime();
$.ajax({
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/ResizeEvents",
dataType: "json",
data: "{'id':'" + event._id + "','end':'" + event.end.format("DD MMMM YYYY HH:mm:ss") + "','allDay':'" + event.allDay + "'}",
});
},
select: function(start, end, allDay) {
$modal.modal({
backdrop: 'static'
});
form = $("<form></form>");
form.append("<div class='row'></div>");
form.find(".row")
.append("<div class='col-md-6'><div class='form-group'><label class='control-label'>Event Name</label><input class='form-control' placeholder='Insert Event Name' type='text' name='title'/></div></div>")
.append("<div class='col-md-6'><div class='form-group'><label class='control-label'>Category</label><select class='form-control' name='category'></select></div></div>")
.find("select[name='category']")
.append("<option value='busy'>Busy</option>")
.append("<option value='e1'>E1</option>")
.append("<option value='e2'>E2</option>")
.append("<option value='bg-blue'>Lunch</option>")
.append("<option value='bg-yellow'>Children</option></div></div>");
inputSelect();
$modal.find('.delete-event').hide().end().find('.save-event').show().end().find('.modal-body').empty().prepend(form).end().find('.save-event').unbind('click').click(function() {
form.submit();
});
$modal.find('form').on('submit', function() {
title = form.find("input[name='title']").val();
beginning = form.find("input[name='beginning']").val();
ending = form.find("input[name='ending']").val();
$categoryClass = form.find("select[name='category'] option:checked").val();
var allDay = !start.hasTime() && !end.hasTime();
if (title !== null && title.length != 0) {
//calendar.fullCalendar('renderEvent', {
// title: title,
// start:start,
// end: end,
// allDay: false,
// className: $categoryClass
//}, true);
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/CreateCalendarEvent",
dataType: "json",
data: "{'title':'" + title + "','start':'" + start.format("DD MMMM YYYY HH:mm:ss") + "','end':'" + end.format("DD MMMM YYYY HH:mm:ss") + "','category':'" + $categoryClass + "','allDay':'" + allDay + "'}",
success: function(data) {
var obj = data.d;
if (obj == 'true') {
//$('#txtFirstName').val('');
//$('#txtLastName').val('');
//$('#txtCity').val('');
//$('#txtEmailID').val('');
//$('#lblmsg').html('Data Inserted Successfully');
}
},
error: function(result) {
alert(result);
}
});
calendar.fullCalendar('refetchEvents')
$modal.modal('hide');
} else {
alert('You have to give a title to your event');
}
return false;
});
calendar.fullCalendar('unselect');
}
});
/* Creation of new category */
$('.save-category').on('click', function() {
formCategory = $('#add-category form');
var categoryName = formCategory.find("input[name='category-name']").val();
var categoryColor = formCategory.find("select[name='category-color']").val();
if (categoryName !== null && categoryName.length != 0) {
$('#external-events').append('<div class="external-event bg-' + categoryColor + '" data-class="bg-' + categoryColor + '" style="position: relative;"><i class="fa fa-move"></i>' + categoryName + '</div>')
runCalendar();
}
});
}
$(function() {
runCalendar();
});
Instead of:
events: "calendar.asmx/EventList",
following method can disable the cache
eventSources: [{
url: 'calendar.asmx/EventList',
type: 'POST',
cache: false
}],
According to FullCalendar documentation your call already prevents the browser from caching, and the fact that FullCalendar is a jQuery plugin means that under the hood it probably uses jQuery's $.ajax() method to retrieve the data.
In my case I had to turn off both lazyFetching and events cache:
eventSources: [
{
url: ...,
cache: false,
}
],
lazyFetching: false

Using Ajax, Jquery inserting data in database in Asp.Net?

![enter image description here][1]In asp.net, I am trying to insert data using Ajax, Jquery but I am not getting insert data in database, when I place break point at a method but compiler is not coming at break point. Please help me, I am placing the code.
<script type ="text/javascript" >
$(document).ready(function () {
$('#btns').click(function () {
var firstname = $('#<%= txtFirstname.ClientID %>').val();
var phonenumber = $('#<%= txtphonenumber.ClientID %>').val();
var orgtype = $('#<%= ddlOrgatype.ClientID %>').text();
var orgisaname = $('#<%= txtorganame.ClientID %>').val();
var orgnisemail = $('#<%= txtorgemail.ClientID %>').val();
var stateid = $('#<%= ddlstate.ClientID %>').val();
var districtid = $('#<%= ddlDistrict.ClientID %>').val();
var location = $('#<%= txtlocatio.ClientID %>').val();
var userid = $('#<%= txtusername.ClientID %>').val()
var password = $('#<%= txtpassword.ClientID %>').val();
$.ajax({
type:'POST',
contentType: "application/json; charset=utf-8",
url: "Registrationpage.aspx/InsertData",
data: "{'firstname':'" + firstname + "','phonenumber':'" + phonenumber + "','Organitype':'" + orgtype + "','OrgnaisaName':'" + orgisaname + "','OrgnaisaEmail':'" + orgnisemail + "','Stateid':'" + stateid + "','Districtid':'" + districtid + "','Location':'" + location + "','Userid':'" + userid + "','passowrd':'" + password + "'}",
dataType: "json",
success: function(data) {
alert('Inserted');
$('#dvreslt').html = "Inserted Successfully";
} ,
error: function (data) { alert(Error) }
});
});
});
//////////
[WebMethod]
protected static string InsertData(string firstname, string phonenumber, string Organitype, string OrgnaisaName, string OrgnaisaEmail, string Stateid, string Districtid, string Location, string Userid, string passowrd)
{
IBusinessLogic iBusinessLogic = BLFactory.GetBLObject(BLObjectType.Register);
BusinessService businessService = new BusinessService();
RegisterDO objRegisterDO = new RegisterDO();
objRegisterDO.UserName = firstname; objRegisterDO.MobileNo = phonenumber; objRegisterDO.organisationType = Organitype;
objRegisterDO.OrganisationName = OrgnaisaName; objRegisterDO.OrganisationEmail = OrgnaisaEmail; objRegisterDO.StateID = Convert.ToInt32(Stateid);
objRegisterDO.Distictid = Convert.ToInt32(Districtid); objRegisterDO.Location = Location; objRegisterDO.UserID = Userid; objRegisterDO.Password = passowrd;
businessService.BusinessLogic = iBusinessLogic;
if (businessService.Execute(OperationType.Create, objRegisterDO))
{
return "inserted";
}
else
return "fasle";
}
I correct your data in request. It passing how javascript object
$.ajax({
type:'POST',
contentType: "application/json; charset=utf-8",
url: "Registrationpage.aspx/InsertData",
data: { firstname: firstname, phonenumber: phonenumber,
Organitype: orgtype, OrgnaisaName: orgisaname,
OrgnaisaEmail: orgnisemail,
Stateid: stateid, Districtid: districtid,
Location: location,
Userid: userid, passowrd: password }
dataType: "json",
success: function(response) {
alert('Inserted');
$('#dvreslt').html = "Inserted Successfully";
} ,
error: function (response) { alert('Error') }
});

How to make texbox to null after I got success in jQuery AJAX method

I am strangling when I added my comments with AJAX method of jQuery, after stressful, I want to make this textbox to null
my Ajax method like this :
function AddComments() {
$(".Comment input[type=text]").keypress(function (e) {
if (e.which == 13) {
var comment = $("#" + this.id).val();
var textId = "#" + this.id.replace("txt", "div");
$(textId).append(comment);
$.ajax({
type: "POST",
url: "Posts.aspx/AddComments",
data: "{'id': '" + this.id.replace("txt", "") + "','comments': '" + comment + "'}",
dataType: "json",
contentType: "application/json",
success: function (response) {
$("#" + this.id).val("");
//alert(response.d);
}
});
}
});
}
what I want is on Success, I want make current textbox to NULL
$("#" + this.id).val("");
This is a scoping issue. this in the success handler holds a reference to the window object, not the input the keypress fired on. You just need to cache the input in a variable you can use in the success handler. Try this:
function AddComments() {
$(".Comment input[type=text]").keypress(function (e) {
if (e.which == 13) {
var $input = $(this);
var comment = $input.val();
var textId = "#" + this.id.replace("txt", "div");
$(textId).append(comment);
$.ajax({
type: "POST",
url: "Posts.aspx/AddComments",
data: "{'id': '" + this.id.replace("txt", "") + "','comments': '" + comment + "'}",
dataType: "json",
contentType: "application/json",
success: function (response) {
$input.val("");
//alert(response.d);
}
});
}
});
}
you can't access this in jquery ajax do it like this save your object in any variable
function AddComments() {
$(".Comment input[type=text]").keypress(function (e) {
if (e.which == 13) {
var Element=this;
var comment = $("#" + this.id).val();
var textId = "#" + this.id.replace("txt", "div");
$(textId).append(comment);
$.ajax({
type: "POST",
url: "Posts.aspx/AddComments",
data: "{'id': '" + this.id.replace("txt", "") + "','comments': '" + comment + "'}",
dataType: "json",
contentType: "application/json",
success: function (response) {
$(Element).val("");
//alert(response.d);
}
});
}
});
}
Your success function is in another context, you can't use this, you have to send the id on the json response and do something like:
success: function (response) {
$('#'+response.div_id).val("");
}
and your json response should include the div_id that's passed on the ajax request

JSON is undefined in IE7

It works fine in chrome, firefox and IE8. But comes up an error on IE7. Here is my jquery onchange event.
$('select#NationId').change(function () {
var nationId = $(this).val();
$.ajax({
url: 'LoadAreas',
type: 'POST',
data: JSON.stringify({ nationId: nationId }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$('select#AreaId').get(0).options.length = 0;
$('select#AreaId').append('<option value="0">Select All</option>');
$.each(data, function (val, Areas) {
$('select#AreaId').append('<option value="' + Areas.Id + '">' + Areas.Name + '</option>');
});
}
});
});
controller
[HttpPost]
public ActionResult LoadAreas(int nationId)
{
var _Areas = (from c in SessionHandler.CurrentContext.ChannelGroups
join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
where cgt.Name == "Area" && c.ParentChannelGroupId == nationId
select new AreaName() { Id = c.ChannelGroupId, Name = c.Name }).OrderBy(m => m.Name);
if (_Areas == null)
return Json(null);
List<AreaName> managers = (List<AreaName>)_Areas.ToList();
return Json(managers);
}
The issue is that the JSON object is not available in IE 7. You'll want to include JSON2.js on your page for IE < 8 users.
If the browser doesn't implement the JSON object, you can always use a third-party library to provide it for you. If I recall correctly, this particular implementation is widely used and defers to the browser, so you just need to drop it in, no tweaking required.
Shouldn't
data: { "nationId": nationId },
just work?
$('select#NationId').change(function () {
var nationId = $(this).val();
var data = '{"nationId": "' + nationId + '"}';
$.ajax({
url: 'LoadAreas',
type: 'POST',
data: data ,
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$('select#AreaId').get(0).options.length = 0;
$('select#AreaId').append('<option value="0">Select All</option>');
$.each(data, function (val, Areas) {
$('select#AreaId').append('<option value="' + Areas.Id + '">' + Areas.Name + '</option>');
});
}
});
});

passing multiple values from multiple textboxes in jquery

Below is the jquery script that takes one input value from textBox1 and pass it to a web method then returns the name of the person and displays it in textBox2. The web method only takes one parameter, the user initials.
<script type="text/javascript" >
$('#textBox1').live('keydown', function(e) {
var keyCode = e.keycode || e.which;
if (keyCode == 9) {
e.preventDefault();
$.ajax({
type: "POST",
url: "Default.aspx/GetName",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{"value1":"' + $('#textBox1').val() + ' " }',
success: function(data) {
$('#textBox2').val(data.d);
}
});
}
});
</script>
I want to be able to pass two values from two textboxes for a web method that requires two parameters. how can I modify the jquery code above to accomplish that?
You add the parameters to the data object, which by the way should be an object:
data: { value1: $('#textBox1').val(), value2: $('#textBox2').val() },
Is this what you mean?
<script type="text/javascript" >
$('#textBox1').live('keydown', function(e) {
var keyCode = e.keycode || e.which;
if (keyCode == 9) {
e.preventDefault();
$.ajax({
type: "POST",
url: "Default.aspx/GetName",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{"value1":"' + $('#textBox1').val() + '", "value2":"' + $('#textBox2').val() + '" }',
success: function(data) {
$('#textBox2').val(data.d);
}
});
}
});
</script>
I'd use something like jQuery Json

Resources