Reinitialze onChange event for Bootstrap multiselect - javascript

I have a series of multiselect dropdown controls. The first one (users) causes the second one (userGroups) to update when one of its values is changed and the second one (userGroups) causes the third one (theaters) to update the contents of its list.
The onChange event for the first dropdown (users) is working fine. But, the second one (userGroups) onChange event is not firing when one of it's values is changed and thereby not updating the list of the third dropdown (theaters).
I know from having worked with Javascript, the onChange needs to be reinitiazed; but, I do not know how to do this with the Bootstrap multiselect. My code follows:
$('.users').multiselect({
numberDisplayed: 1,
maxHeight: 400,
includeSelectAllOption: false,
enableCaseInsensitiveFiltering: true,
filterBehavior: 'both',
disableIfEmpty: true,
onChange: function (element, checked) {
var userName = $('.users').val();
if (userName != null) {
userName = userName.toString();
}
$.ajax({
url: '#Url.Action("LoadUserGroups")',
data: { "userName": userName },
success: function (data) {
$('.userGroups').multiselect('destroy');
$('.userGroups').replaceWith($(data));
$('.userGroups').multiselect('rebuild');
},
error: function (xhr) {
$('.userGroups').multiselect('destroy');
$('.userGroups').multiselect('rebuild');
}
});
}
});
$('.userGroups').multiselect({
numberDisplayed: 1,
maxHeight: 400,
includeSelectAllOption: false,
enableCaseInsensitiveFiltering: true,
filterBehavior: 'both',
disableIfEmpty: true,
onChange: function (element, checked) {
javascript: console.log("OnChange event fired");
var groupId = $('.userGroups').val();
if (groupId != null) {
groupId = groupId.toString();
}
$.ajax({
url: '#Url.Action("LoadTheaters")',
data: { "groupId": groupId },
success: function (data) {
$('.theaters').multiselect('destroy');
$('.theaters').replaceWith($(data));
$('.theaters').multiselect('rebuild');
},
error: function (xhr) {
$('.theaters').multiselect('destroy');
$('.theaters').multiselect('rebuild');
}
});
}
});
});
If anyone can show me how to do this or at least point me in the right direction, I would much appreciate it. Thanks in advance.

Ok -- I got it to work. Here is what I was doing before:
$.ajax({
url: '#Url.Action("LoadUserGroups")',
data: { "userName": userName },
success: function (data) {
$('.userGroups').multiselect('destroy');
$('.userGroups').replaceWith($(data));
$('.userGroups').multiselect('rebuild');
},
error: function (xhr) {
$('.userGroups').multiselect('destroy');
$('.userGroups').multiselect('rebuild');
}
});
I made the following changes that maintained the userGroups dropdown so the onChange event would fire:
$.ajax({
url: '#Url.Action("LoadUserGroups")',
data: { "userName": userName },
success: function (data) {
$('.userGroups').empty();
$('.userGroups').append($(data).find('option'));
$('.userGroups').multiselect('rebuild');
},
error: function (xhr) {
$('.userGroups').empty();
$('.userGroups').multiselect('rebuild');
}
});
Works like it should now.

Related

Jquery Autocomplete not populating after error thrown

I am running a ASP.Net MVC application and using jQuery's Autocomplete in one of the textboxes to populate contract numbers after the 6th digit/character.
It is working flawlessly, until after an error is thrown for a validation check.
My code :
$(document).ready(function () {
$("#ContractNumber").autocomplete({
source: '#Url.Action("GetContractId")',
open: function () { $('ul.ui-autocomplete').hide().fadeIn() },
close: function () { $('ul.ui-autocomplete').show().fadeOut() },
minLength:6
});
});
The code that redirects to the correct controller to get the contract number is here:
$(document).ready(function () {
//$('body').on('focus', "#ContractNumber", function () {
$("#ContractNumber").autocomplete({
source: function (request, response) {
$.ajax({
url: "/PurchaseRequestDetail/GetContractId",
minLength: 1,
data: { Prefix: request.term },
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };;
}))
}
})
}
});
Here is the autocomplete that is working fine, before the error:
I wanted this autocomplete to work, on focus of the textbox, whether a validation error thrown or not.
validation error:
The code that checks for ModelState if contract number is not found :
if (contractNo is null)
{
// row.ContractId = foundList.ContractId;
db.PurchaseRequestDetail.Add(newRow);
db.SaveChanges();
}
else if (contractNo != null)
{
if (foundList is null)
{
ModelState.AddModelError("ContractNumber", "Contract Number not in the database.");
// reload the drop down lists, they don't survive the trip to the server and back
viewModel.ContractList = GetContractList(viewModel.ContractId);
return View("CreateEdit", viewModel);
}
}
Any pointers in correcting this would be helpful.
TIA.

How change the dropdown values dynamically

HI I am using davidstutz bootstrap-multiselect plugin,i want to update the values of department dropdown based on Client dropdown value
following is he code for Client Dropdown (C# ASP.Net Format)
#Html.DropDownList("ClientID", null, "Select Client", new { #class = "form-control",#required="required" })
Code for Department dropdown
<select id="Agents[0].Departments" name="Agents[0].Departments" class="form-control AgentDepartments" multiple>
</select>
Initially i am applying the plugin and on client change i am re assigning the plugin but it is not updating the department dropdown values
Jquery Code
$(function () {
$('.AgentDepartments').multiselect({
includeSelectAllOption: true,
height: '20px'
});
$("#ClientID").on('change',function () {
var CIN = $('option:selected', this).text();
$.ajax({
type: "get",
url: '/Client/GetDepartmentList',
contentType: "application/json; charset=utf-8",
data: { "CIN": CIN },
datatype: "json",
success: function (data) {
$('.AgentDepartments').empty();
$.each(data, function () {
$(".AgentDepartments").append($("<option/>").val(this.KeyName).text(this.ValueName));
});
$('.AgentDepartments').multiselect({
includeSelectAllOption: true,
height: '20px'
});
},
error: function () {
alert("Failed to load Data.");
toastr.warning('Something went wrong!', null, { "closeButton": true });
},
beforeSend: function () {
$('#loadingDiv').show();
},
complete: function () {}
});
});
});
Instead of doing this
$('.AgentDepartments').multiselect({
includeSelectAllOption: true,
height: '20px'
});
Try Rebuilding the dropdown
$('.AgentDepartments').multiselect('rebuild')
I think, you first need to destroy and then reinitialize after changing/appending the options:
$(".AgentDepartments").append(toAppend).multiselect("destroy").multiselect();
Alternatively, I think, you can also:
$(".AgentDepartments").append(toAppend).multiselect('refresh');

Error: object doesn't support 'autocomplete'

I have this function using the jquery autocomplete widget, that I am getting the following error:0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'autocomplete'
On my html page, in the head section I have included the following tags.
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/jquery-ui-1.11.4.min.js"></script>
The function is called by a variety of option button calls to do several different query's. I have this function in a different application that works well but here it is not.
function AutoComplete(Type) {
//create AutoComplete UI component
$("#txtCriteria").autocomplete({
source: function (request, response) {
$.ajax({
autoFocus: true,
async: false,
delay: 250,
url: "wsReports.asmx/AutoComplete",
data: "{'Type':'" + Type + "', 'filter':'" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.ACName,
value: item.ACCode
} // end of return
})) // end of response
} // end of success
}); // end of ajax
}, // end of source
select: function (event, ui) {
if (ui.item.value == "") {
alert("nothing to select");
}
else {
// prevent autocomplete from updating the textbox
event.preventDefault();
// manually update the textbox and hidden field
$(this).val(ui.item.label);
}
}, // end of select
change: function (event, ui) {
if (!ui.item) {
$(event.target).val('');
}
},
}) // end of txtCriteria.autocomplete
} // end of AutoComplete
Any ideas why it is not recognized in the above situation?
My fault. The jquery.js and bootstrap were loading after the jquery-ui.

JQuery autocomplete not working in IE8 -unable to get value from response

I have autocomplete on one textbox. it's working in IE9, firefox, chrome. but not working in IE8.
error msg is :SCRIPT5007: Unable to get value of the property 'question': object is null or undefined.
please read the following code and comments inside. Thanks.
$(function () {
$newdiv.find("input[id$=tbxQuestion]").autocomplete({
source: function (request, response) {
$.ajax({
url: "Services/Questions.ashx",
dataType: "jsonp",
async: false,
data: {
featureClass: "P",
style: "full",
type: "tf",
maxRows: 10,
name_startsWith: request.term
},
success: function (data) {
response($.map(data.questions, function (q) {
//q has values right before here
return {//q is undefined here. try to find the reason.
value:q.question,
answer:q.answer,
opta: q.opta,
optb: q.optb,
optc: q.optc,
optd: q.optd
}
}))
}
})
},
minLength: 4,
delay: 800,
focus: function (event, ui) {
return false;
},
select: function (event, ui) {
$(this).val(ui.item.value);
return false;
}
});
});

Jquery-ui open dialog from js loop

I'm developing a web site with JQuery
I have encountered the following problem:
Going through an array in a loop, and every value is sent to a function that sends it to the server by Ajax.
On success a message is generated in JQuery- Dialog, in which buttons and button- functions are adjusted by the values returned from the server.
The problem is, that the JQuery-dialog is only triggered at the end of the loop, so I cannot tell which message refers to what value.
The loop func:
$('#List').find('option').map(function () {
semelO= $(this).val();
**getData**("Insert_hashala", "Inserthashala", false, "***setAlert***", false, "inserthasala", ["semelO", semelO], null, "RefershLendGrid", null);
});
The function signature:
function **getData**(procAlias, funcName, empytFields, ***onSuccessEvent***, isAsync, dataGroup, moreValues, onFailure, setDisplay, onFailureEvent)
The Ajax
jQuery.ajax({
type: "POST",
contentType: 'application/json',
dataType: "json",
url: "SvcSifria.asmx/" + funcName,
data: dataJsonString,
success: function (data) {
if (onSuccessEvent != undefined) eval(***onSuccessEvent*** + '(data)');
if (setDisplay != undefined) eval(setDisplay + '(data)');
},
async: isAsync
});
}
The Dialog function:
function ***setAlert***(data, error) {
myJson = jQuery.parseJSON(data.d);
text = data.d;
$("#dialog:ui-dialog").dialog("destroy");
$("#dialog-mess").dialog({
autoOpen: false,
modal: true, appendToBody: true,
buttons: [{
text: textButton,
id: "cancle",
click: function () {
$(this).dialog("close");
},text: textButton,
id: "ok",
click: function () {
getData("Insert_hashala", "Inserthashala", false, "setAlert", isAsync, "inserthasala", [returnValue, "true", "sumHashala", sumHashala, "semelOtek", semelOtek], null, "RefershLendGrid");
$(this).dialog("close");
}
}]
});
$("#ok").focus();
$("#dialog-mess").dialog("open");
}

Categories

Resources