How change the dropdown values dynamically - javascript

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');

Related

How to filter Jquery FullCalendar using Ajax reading from aspx web method

Here I am trying to filter the Event Calendar using Location. Tried with different options but no luck. Any Help would be great. I am using one dropdown to filter the Location. On Page load it should be All and selection should filter the location and render the Full Calendar
<script type="text/javascript">
jQuery(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
data: "{}",
url: '<%=ResolveUrl("eventlist.aspx/GetEvents")%>',
dataType: "json",
success: function (data) {
$('#fullcal').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
defaultDate: '2016-09-12',
//editable: true,
displayEventTime: false,// hide event time
eventLimit: true, // allow "more" link when too many events
events: $.map(data.d, function (item, i) {
var event = new Object();
event.id = item.EventID;
event.title = item.EventName;
event.start = new Date(item.StartDate);
event.end = new Date(item.EndDate);
event.loc = item.City;
return event;
}),
eventRender: function eventRender(event, element, view) {
return ['all', event.location].indexOf($('#location').val()) >= 0
}
});
$('#location').on('change', function () {
$('#fullcal').fullCalendar('removeEvents');
var sval = $('#location option:selected').val();
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
data: "{}",
url: '<%=ResolveUrl("eventlist.aspx/GetEvents")%>',
dataType: "json",
success: function(data){
$.each(data,function(index,value){//for each event, I will compare the value with the filter, if true, render it.
if(value.City==sval){
$("#fullcal").fullCalendar('renderEvent', value, true);
}
})
}
});
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
});
</script>
<select id="location">
<option value="all">All</option>
<option value="city1">city1</option>
<option value="city2">city2</option>
<option value="city3">city3</option>
</select>
<div id='fullcal'></div>
Please change the sequence of initialization calendar and then use function events in calendar to provide date by ajax.
So first initialize calendar with property events: function() => $.ajax({....
Full calendar will call your function for data.
Then in event $('#location').on('change' please use function $("#fullcal")fullCalendar('refetchEvents')
Your function to load data has to be aware of selection from the list.
jQuery(document).ready(function () {
$('#location').on('change', function () {
InItCal($('#location option:selected').val());
$('#fullcal').fullCalendar('destroy');
});
$('#fullcal').fullCalendar('destroy'); Just one line of code did the trick and shows the updated events.

Get value from autocomplete dropdown

I need to assign value from dropdown to autocomplete textbox ..till Now I have done this
But You can see I can't assign value from Dropdown to textbox ..
I have implemented auto complete feature by a JQuery PlugIn "Prop.js"
this is the code I have created
<link href="~/Content/popr.css" rel="stylesheet" />
<script src="~/Scripts/popr.js"></script>
<script src="~/Scripts/popr.min.js"></script>
<div id="address" >
<label>Country</label>
<table>
<tr>
<td>#Html.TextBox("Country")</td>
<td>
<div class="popr" data-id="demo">^</div>
<div class="popr-box" data-box-id="demo">
</div>
</td>
</tr>
</table>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#Country").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Location/GetAllCountry",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response(data);
}
})
},
appendTo: '#menu-container',
messages: {
noResults: "", results: ""
}
});
$.ajax({
url: "/Location/GetAllCountry",
type: 'POST',
data: { term: "" },
success: function (states) {
var $select = $('div[data-box-id="demo"]');
$.each(states, function (i, state) {
$('<option>', {
value: state
}).html(state).appendTo($select)
.addClass("popr-item");
});
},
error: function (xhr) { alert("Something seems Wrong"); }
});
});
$('.popr').popr();
$('.popr').popr({
'speed': 200,
'mode': 'bottom'
});
I have searched the solution the tried for a click inside div to get selected value
$(".popr-item").click(function (e) {
e.stopPropagation();
});
$(".popr-box").click(function (e) {
e.stopPropagation();
alert("popr-box");
});
this is not working
I tried another plugin "chosen" .. But it fails in cascading dropdown ..I am not in a position to try another plugin ... I strictly want to use by this way
if there is another plugin available , I need to see example with cascading dropdown specifically
I just need selected value from dropdown , How Can I achieve this ?
Add this select option in autocomplete
$("#Country").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Location/GetAllCountry",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response(data);
}
})
},
select: function( event, ui ) {
$( "#Country" ).val( ui.item.label );
return false;
},
appendTo: '#menu-container',
messages: {
noResults: "", results: ""
}
});

Reinitialze onChange event for Bootstrap multiselect

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.

How to log "select2" selected value

I use "Select2" as dropdown list.
Now i´d like my page content to change upon my choice in Select2.
I´m stepping forward and have come to this:
JS
$(document).ready(function(){
// display logs
function log(text) {
$('#logs').append(text + '<br>');
}
//SELECT2
$( ".select2_choose_objnr" ).select2({
placeholder: "Välj Objekt..",
ajax: {
url: "php.php",
type: "POST",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
}).on("change", function(e) {
log("change val=" + e.val);
});
});
From this Js, i got: val=undefined
How can i change my code to get the selected value/text ?
For v4.0.3
In the change callback, call $(this).val() to retrieve an array of selected values
.on("change", function(e) {
log("change val=" + $(this).val());
});
val() is a function, not a property and you want to call it on $(this)
You can accesss the full data
.on('change', function(e) {
// Access to full data
console.log($(this).select2('data'));
});

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