I have 3 drop downs which are cascading.
Zone -- > Region --> Territory
I am using Bootstrap multiselect drop downs.
When i select the Zone drop down the respective regions are to be bound
and simultaneously the newly bound regions' territories are to be bound to the territory drop down.
Here is my drop-down initialisation code.
$('#ddlZone').multiselect({
enableClickableOptGroups: true,
enableCollapsibleOptGroups: true,
enableFiltering: true,
includeSelectAllOption: true,
nonSelectedText: 'Select Zone',
enableCaseInsensitiveFiltering: true,
selectAllNumber: true,
onChange: function(option, checked,select) {
FillRegionsDropdown();
FillTerritoriesDropdown();
}
Here is the code for the above functions.
function FillRegionsDropdown()
{
var Zone=$('#ddlZone').val();
if(Zone != null)
{
Zone= Zone.join(",");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "#Url.Action("BindRegionsOnZonesAjax", "GeoMap")",
data: "{ZoneIds:'" + Zone + "'}",
success: function (Result)
{
$("#ddlRegion").html("");
$('#ddlRegion').multiselect( 'refresh' );
$.each(Result, function (key, value) {
$("#ddlRegion").append($("<option></option>").val(value.Value).html(value.Text));
});
$('#ddlRegion').multiselect( 'rebuild' );
$("#ddlRegion").multiselect('selectAll', false);
$("#ddlRegion").multiselect('updateButtonText');
}
});
}
}
The above code works perfectly i.e. on Zone dropdowns change the regions get bound and set to select all.
But the issue is with Binding territory drop down with zone drop down change.
And here is the code for Territory dropdowns binding.
function FillTerritoriesDropdown()
{
var rgns=$('#ddlRegion').val();
if(rgns != null)
{
rgns= rgns.join(",");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "#Url.Action("BindTerritoriesOnRegionsAjax", "GeoMap")",
data: "{RegionIds:'" + rgns + "'}",
success: function (Result)
{
$("#ddlTerritory").html("");
$('#ddlTerritory').multiselect( 'refresh' );
$.each(Result, function (key, value) {
$("#ddlTerritory").append($("<option></option>").val(value.Value).html(value.Text));
});
$('#ddlTerritory').multiselect( 'rebuild' );
$("#ddlTerritory").multiselect('selectAll', false);
$("#ddlTerritory").multiselect('updateButtonText');
}
});
}
}
Here the $('#ddlRegion').val() doesn't get updated to the newly bound region values which is caused due to zone drop down change.
$('#ddlRegion').val() still contains the initial page load region values.
I have been struck with this for more than 6 hours now.
Can some one help me to fix this issue?,
Try using async:false in both FillTerritoriesDropdown() and FillREgionsDropdown() functions. i.e. in the ajaxcalls to the controller of those 2 functions.
Related
So i have a function running an Ajax call that receives data and populate that as a table.
The response contains some rows with data and i now want to add a small fontawsome icon that when clicked fires another function with a parameter.
So i have this:
var latestprecasedata = '';
function getPreCaseData() {
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "case.aspx/GetPreCase",
dataType: "json",
success: function (response) {
if (response != null && response.d != null) {
var data = response.d;
data = $.parseJSON(data);
$("#PreCaseTblBody").html("");
for (var i in data) {
$("#PreCaseTblBody").append("<tr><td>" + data[i].pSubject + "</td><td><span class='preplus' id='" + data[i].pID + "'><i class='fa fa-plus'></i></span></td><td>-</td></tr>");
}
if (latestprecasedata !== response.d) {
$("#precasestatus").removeClass("titleupd1").addClass("titleupd2");
latestprecasedata = response.d;
}
else {
$("#precasestatus").removeClass("titleupd2").addClass("titleupd1");
}
}
$("#PreCaseTblBody tr:odd").css('background-color', '#f9f9f9'); //
$("#PreCaseTblBody tr:even").css('background-color', '#f1ffee');
setTimeout(getPreCaseData, 10000);
}
});
}
This works and every 10 seconds data is repopulated. (Maybe not the fastest solution, but it works..)
As you all can se i have a span with class=preplus and id of a unique value coming from my Ajax response. When inspecting the page i can see that every row from my Ajax response have a unique id.
For example two row looks like this:
<tr><td>Cables</td><td><span class="preplus" id="4815269"><i class="fa fa-plus"></i></span></td></tr>
<tr><td>Skrews</td><td><span class="preplus" id="4815269"><i class="fa fa-plus"></i></span></td></tr>
So now i have the data populated with span containing a unique id that i want to pass to another function.
I've tried span, div, buttons but the only one time I actually got a event fire was when i placed my second function inside the
for (var i in data) {
... and i know, that's not right at all because all rows contained the last id obviously...
So my other function resides outside my first function and look like this (I've tried many different methods to get the id of my span but for now, I'm here)
$(".preplus").click(function () {
var qID = $(this).attr('id');
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "case.aspx/UpdateQ",
dataType: "json",
data: "{'qid':'" + qID + "','pm':'plus'}",
success: function (data) {
}
});
return false;
});
Please guide me.
I have the following code and it works well in JSfiddle, but it doesn't work properly on my web page.
On this page, I have dropdown "B" which is populated based on the selected item in dropdown "A". In case of changing "A" items, values of the second dropdown changed correctly but its default text remains unchanged until I change the selected item in the second dropdown manually.
code:
function get_child() {
$("#child").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("Get_child", "Home")',
dataType: 'json',
data: { Name: $("#parent").val() },
success: function (states) {
$("#child").append('<option value="0" selected="selected"> </option>');
$.each(states, function (i, state) {
$("#child").append('<option value="' + state.Text + '">' +
state.Text + '</option>');
});
},
error: function (ex) {
}
});};
I am facing an issue as below.
I have two drop-down, first one is single drop down select, second one is multi select drop-down checkbox. Second one shows the result based on the first drop-down value.
While select the first drop-down, I get the values for second drop-down to show(Values Show in Inspect element) but not in drop down.
Please find the below code for further reference.
abc.html
<select name="list_usergroup[]" multiple id="list_usergroup" >
<option value=""> Select User Group </option>
</select>
mg.js
org_uuid = $('#list_organization').val();
$.ajax({
url: appGetSecureURL("/api/web/getorgug/" + org_uuid),
type: "GET",
dataType: "json",
jsonpCallback: 'jsonCallback',
beforeSend : function(){
loaderOn();
},
success: function(data) {
// Display Usergroups
if (0 == data.ug_total) {
$("#list_usergroup").html('<option value="">No Usergroup.</option>');
}
else {
$("#list_usergroup").html("");
$("#list_usergroup").html('<option value="">Select Usergroup</option>');
for (rowData in data.usergroups)
{
var optionData = '<option data = "'+ data.usergroups[rowData] +'" value="'+ rowData+'">' + data.usergroups[rowData]+'</option>';
$('#list_usergroup').val("");
$('#list_usergroup').multiselect('refresh');
$('#list_usergroup').multiselect('reset');
$("#list_usergroup").append(optionData);
}
//$('#list_usergroup').multiselect('reset');
$("#list_usergroup").multiselect({
columns: 1,
placeholder: 'Select Usergroups',
search: true,
selectAll: true,
onLoad: function() {
}
});
$("#list_usergroup").val(Value);
}
loaderOff();
},
error: function(data, b, c) {
appLog.debug("Display Usergroup error Status " + data.status + ": " + data.statusText)
}
})
I am using https://github.com/nobleclem/jQuery-MultiSelect plugin
Thanks in advance.
To Enable Multiselect with refresh data. you have to re-initialise Multiselect.
$('#list_usergroup').multiselect('destroy'); // tell widget to clear itself
$('#list_usergroup').multiselect(); // re-initialize the widget
I have a modal that displays a table. And I use datatable plugin so that the data is searchable and sortable. It works properly at first but when I close the modal and click other link to the same modal, it displays error. I have found solution to destroy the DataTable and I put the destroy() before the initialization of the datatable but then no data is displayed inside the table.. if I put it after the initialization it gave me the initialization error the second time I click the button. How am I going to solve this?
here's my code:
$.ajax({
url: "<?php echo site_url('admin/group/getMember')?>",
type: 'POST',
data: { 'groupID': id},
dataType: 'JSON',
success: function(result){
$('#records_table tbody').empty();
// $('#records_table').DataTable({
// "bLengthChange": false,
// "paging":false,
// });
$('.modal-header #hdrmsg').text(result[0].fname);
var trHTML='';
$.each(result, function (i, item) {
trHTML += '<tr><td>' + item.fname + '</td><td>' + item.mname + '</td><td>' + item.lname + '</td></tr>';
});
$('#records_table tbody').append(trHTML);
$('#records_table').DataTable({
"bLengthChange": false,
"paging":false,
});
$('#records_table').DataTable().fnDestroy();
}
});
The main reason for destroying a dataTables instance is if you want to change the initialisation options - like change paging and so on. Or if the table structure should be altered. None of those circumstances seems to be the case here? To answer the question, the safest way to destroy and reinitialise a table is to use the shorthand option destroy: true :
var table = $('#records_table').DataTable({
...
destroy : true
});
To go further, I think you are doing it a little backwards.
Why empty the table with jQuery $('#records_table tbody').empty(); instead of table.clear() ?
Why inject records with jQuery $('#records_table tbody').append(trHTML); instead of using table.row.add([...]) ?
Here is a code scenario similar to the one in the question, which reinitialises the dataTable without conflicts, each time the modal is shown :
var table;
$('#modal').on('show.bs.modal', function() {
$.ajax({
url: url,
dataType: 'JSON',
success: function(response) {
var response = $.parseJSON(response.contents);
//clear the table, if it exists
if (table) table.clear();
//reinitialise the dataTable
table = $('#records_table').DataTable({
destroy: true,
bLengthChange: false,
paging: false
});
$.each(response, function(i, item) {
console.log("inserting", item);
table.row.add([
item.name,
item.position
]).draw();
});
}
});
});
see demo -> http://jsfiddle.net/bz958dxj/
But you really dont need to destroy the table at all, it just slows down performance :
//global table object
table = $('#records_table').DataTable({
bLengthChange: false,
paging: false
});
$('#modal').on('show.bs.modal', function() {
$.ajax({
url: url,
dataType: 'JSON',
success: function(response) {
var response = $.parseJSON(response.contents);
//clear the table
table.clear();
//insert data
$.each(response, function(i, item) {
console.log("inserting", item);
table.row.add([
item.name,
item.position
]).draw();
});
}
});
});
demo -> http://jsfiddle.net/8mjke9ua/
NB: I just assume we are talking about bootstrap modals, based on the reference to .modal-header in the question.
NBĀ²: Notice the $.parseJSON(response.contents), you should do it as you are doing it in the question. The only reason for this is that the examples go trough a proxy to avoid the same-origin policy.
I'm trying to convert some of my code to reusable plugins.
Many times I'm filling selects with dynamic options that comes from Ajax request.
I've managed to create something like this:
$.fn.fillSelect = function fillSelect(options) {
var self = this;
options = $.extend({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Data.asmx/StatusList",
dataType: "json",
async: true,
success: function(data) {
var list = "";
$.each(data.d, function(i) {
list += '<option value='
+ data.d[i].ID + '>'
+ data.d[i].Nazwa
+ '</option>';
});
self.filter("select").each(function() {
$(this).empty();
$(this).append(list);
//use selectmenu
if ($.ui.selectmenu) $(this).selectmenu();
});
}//,
//error: function(result) {
// alert("Error loading data!");
//}
}, options);
$.ajax(options);
return self;
}
Idea behind this is to be able to fill multiple selects with the same data multiple times with one request.
I have default options for Ajax request, but I would like to add some more options to it.
For example:
clear - fill determinate if I want new options to replace existing ones or append.
Also I would like to add some callbacks to my function that I could pass as parameters.
If for example server request will fail I would like to specify a function that will be called after this error occurs - for example to show alert or disable my selects.
My question is how should I change my plugin or which pattern (boilerplate) I should use?
Every boilerplate I found is for creating plugins that will 'stay' inside selected item, so that it is possible to call method of that plugin later.
I need a simple plugin that will allow user to fill select and then it will end it's life :)
My main idea is to do only one request to server for all elements.
Here is jsfiddle demo: http://jsfiddle.net/JC7vX/2/
A basic plugin can be built as follows
(function ($){
$.fn.yourPlugin = function (options){
// this ensures that function chaining can continue
return this.each(function (){
// merge defaults and user defined options
var params = $.extend({},defaultOptions,options);
// your plugin code
});
}
/* these options will help define the standard functionality of the plugin,
* and also serves as a nice reference
*/
var defaultOptions = {
someProperty : true
}
})(jQuery)
There are other things that you can do to extend the functionality of your plugin and give public methods that retain the context, but that would be overkill for your example.
This is my version of answer http://jsfiddle.net/Misiu/ncWEw/
My plugin looks like this:
(function($) {
$.fn.ajaxSelect = function(options) {
var $this = this;
//options
var settings = $.extend({}, defaults, options);
//disable select
if ($.ui.selectmenu && settings.selectmenu && settings.disableOnLoad) {
$this.selectmenu('disable');
}
//ajax call
$.ajax({
type: settings.type,
contentType: settings.contentType,
url: settings.url,
dataType: settings.dataType,
data: settings.data
}).done(function(data) {
var n = data.d || data;
var list = "";
$.each(n, function(i) {
list += '<option value=' + n[i].Id + '>' + n[i].Nazwa + '</option>';
});
$this.filter("select").each(function() {
$(this).empty();
$(this).append(list);
if ($.ui.selectmenu && settings.selectmenu) {
$this.selectmenu();
}
settings.success.call(this);
});
}).fail(function() {
settings.error.call(this);
});
return this;
};
var defaults = {
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/echo/json/',
dataType: 'json',
data: null,
async: true,
selectmenu: true,
disableOnLoad: true,
success: function() {},
error: function() {}
};
})(jQuery);
I understand that it is very simple, but it has all functionality that I needed:
-You can select multiple elements at one time
-It filters only selects from Your selected items
-It makes only one request to server
-First it builds option string and then append it instead of adding items in loop
-You can specify 2 callbacks: one for error and second for success
And it is my first plugin, so there is much places for improvements.
As always comments and hints are welcome!