In my mvc view I have a DropDownList that gets values from a dictionary
<div class="InputPart">
#(Html.Telerik().DropDownListFor(model => model.PasportAddressRegionID)
.Name("ddlfRegions1")
.BindTo(new SelectList((IEnumerable<Dictionary>)ViewData["Regions"], "ID", "Title"))
.ClientEvents(e => e.OnChange("changeRegion1"))
.HtmlAttributes(new { style = "min-width:200px" }))
</div>
and I have JS function changeRegion1() that gets these values.
<script type="text/javascript">
function changeRegion1() {
var rgnId = $('#ddlfRegions1').data('tDropDownList').value();
$.ajax({
url: '#(Url.Action("_GetDistrict", "Staffs"))',
data: { regionId: rgnId },
type: "POST",
success: function (result) {
var combobox = $('#ddlfDistricts1').data('tDropDownList');
combobox.dataBind(result);
combobox.enable();
}
});
} </script>
I put the function in the same view, below all the code, but when run I got Uncaught ReferenceError: changeRegion1 is not defined. The function itself is OK, but it seems to me that event handler does not see it here.
So I just wonder what is wrong here? And how should I reference the function?
Any help is appreciated
Here is an example for the Kendu UI Dropdown list Event handling for ASP.Net and MVC. Compare to your code. The example shows Events, you call ClientEvents otherwise looks ok.
http://docs.telerik.com/aspnet-mvc/helpers/dropdownlist/overview
#(Html.Kendo().DropDownList()
.Name("dropdownlist")
.BindTo(new string[] { "Item1", "Item2", "Item3" })
.Events(e => e
.Select("dropdownlist_select")
.Change("dropdownlist_change")
)
)
<script>
function dropdownlist_select() {
//Handle the select event.
}
function dropdownlist_change() {
//Handle the change event.
}
Related
In my django app I have a WorkerModel and a ProvinceModel, each worker has a province_id field. I have define a form for Worker using ModelSelect2Widget (django_select2) for province_id. I want to know how to set a value to province_id field using javascript.
I have tried with:
$('#id_province_id').val(province_id).trigger('change');
but is not working.Here is the defintion of my form
from django_select2.forms import ModelSelect2Widget
class WorkerForm(forms.ModelForm):
class Meta:
model = WorkerModel
exclude = ("id",)
widgets = {
'name':forms.TextInput(attrs={'class': 'form-control'}),
'province_id' : ModelSelect2Widget(model=ProvinceModel, queryset=ProvinceModel.objects.filter(),
search_fields=['des_prov__icontains'],
attrs={'style': 'width: 100%;'}),
}
in the template
<script>
//on a button click a want to set the value of province_id
$(document).ready(function () {
$('#id_province_id').djangoSelect2({
placeholder: 'Seleccione una opciĆ³n',
escapeMarkup: function (markup) { return markup; },
language: {
noResults: function () {
return "No se encuentran resultados.";
}
}
});
});
</script>
You can try this on your ajax success function:
success: function(data){
// Assumes that data.result is your proovince id
if(data.hasOwnProperty('result')){
$('#id_province_id').val(data.result).trigger('change');
}
}
I'm using selectize.js for remote search and get options against that search for my select input.
I've seen example code in their demo
<script type="application/javascript">
$(function () {
$('#workers_paid').selectize({
placeholder: "No worker Is selected",
valueField: "name",
labelfield : "name",
searchField: 'name',
render: {
option: function (item,escape) {
console.log(item);
}
},
onLoad : function (data) {
}
,
load: function (query, callback) {
alert(query);
let data = JSON.parse('{"users" : [{"user_name": "Humza"},{"user_name": "Humza"},{"user_name": "Humza"},{"user_name": "Humza"},{"user_name": "Humza"},{"user_name": "Humza"}]}');
callback(data.users);
}
});
});
</script>
This is my code that i've written for loading a static data but still render is not logging any data in console .... Onload function is also working just render is not calling anything or any options is not being created.
Sorry for bad english and thanks in advance
I have some search filters for a query in my application. From the filters I want to render the json results into a kendo grid. For that reason I don't use the default DataSource.Read() of the grid but an Ajax request and I bind the results to the grid like that:
Kendo grid:
#(Html.Kendo().Grid<List<SearchSpecialtiesResult>>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.Id).Hidden();
columns.Bound(c => c.Code).Width(100);
// Some other columns
})
//Some events and filtering options
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
.Model(model =>
{
model.Id(p => p.Id);
// other model values
})
)
)
Set the dataSource on Ajax success
var datasource = new kendo.data.DataSource({ data: resultData });
$("#grid").data("kendoGrid").setDataSource(datasource);
The binding happens correctly however to other places that I use the DataSource.Read() the grid shows a loading effect that I can't find how to reproduce to my page and I use to this place some other loading effect we use on Ajax requests. Is there any way to reproduce it in my case?
I had such cases in my application too. The way I handled them was also by kendo.ui.progress($("#gridDame"), true). For the sake of the completion of the answer I will post the way I handled them and the way I am handling them now with the DataSource.Read() of the grid by passing the filter input values as additional data to my Read request.
First way:
I had a general Ajax call for all my gridRequests
function getGridData(uri, payload, gridName) {
return $.ajax({
url: uri,
type: "POST",
contentType: "application/json",
data: payload,
beforeSend: function () {
window.kendo.ui.progress($("#"+ gridName), true);
}
}).done(function (result) {
return result;
}).always(function () {
window.kendo.ui.progress($("#" + gridName), false);
});
}
I called it on my button click with the parameters of my search form
$("#searchFormBtn").bind("click", function (e) {
e.preventDefault();
// ... Get the filter input values and strignify them as json ...
return getGridData(url, filterInputValuesStrignifiedAsJson, "grid")
.done(function (result) {
if (result.success) {
var datasource = new kendo.data.DataSource({ data: result.data });
$("#grid").data("kendoGrid").setDataSource(datasource);
} else {
//Handle error
}
});
});
Second way:
I set my Datasource.Read() like this:
.Read(read => read.Action("ActionName", "ControllerName").Data("getFilterInputValues"))
and always Autobind(false) in order not to read on first load
In the function getFilterInputValues I get my search form values like that:
function searchModelData() {
return {
DateFrom: $("#DateFrom").data("kendoDatePicker").value(),
DateTo: $("#DateTo").data("kendoDatePicker").value(),
Forever: document.getElementById("datesForever").checked === true ? true : false,
SearchCommunicationType: { Id: $("#SearchCommunicationType_Id").val() },
SearchBranch: { Id: $("#SearchBranch_Id").val() },
CompletedById: { Id: $("#CompletedById_Id").val() },
SearchOperationType: { Id: $("#SearchOperationType_Id").val() },
AcademicPeriodSearch: { Id: $("#AcademicPeriodSearch_Id").val() },
AcademicYearSearch: $("#AcademicYearSearch").val(),
Name: $("#Name").val(),
ContactValue: $("#ContactValue").val(),
AddressValue: $("#AddressValue").val()
};
}
Finally I trigger the DataSource.Read() of my grid on the button click
$("#searchFormBtn").bind("click", function () {
var grid = $('#grid').data("kendoGrid");
if (grid.dataSource.page() !== 1) {
grid.dataSource.page(1);
}
grid.dataSource.read();
});
With Datasource.Read() obviously works correctly and the spinning effect you mention in your question.
You're looking for kendo.ui.progress. Click here for Telerik's documentation.
Before running the ajax call add the following to show the loading effect:
kendo.ui.progress($("#gridName"), true);
After success or failure add the following to remove the loading effect:
kendo.ui.progress($("#gridName"), false);
You can do it manualy
<div id="UrGrid"></div>
<div class="chart-loading"></div>
in event:
var loading = $(".chart-loading", e.sender.element.parent());
kendo.ui.progress(loading, true);
...work with data...
kendo.ui.progress(loading, false);
I have been trying to subscribe to when a dropdown value changes. I have the following logic however I cannot seem to get it working.
HTML
<div id="case-pin-#modelItem.CaseID" data-caseid="#modelItem.CaseID" class="row hidden popovercontainer pinBinding">
<select data-bind="options:userPins,
value:selectedPin,
optionsCaption:'-- please select --',
optionsText: 'Name',
optionsValue: 'Id'"></select>
</div>
JS
function UserPinViewModel(caseId) {
var self = this;
self.selectedPin = ko.observable();
self.userPins = ko.observableArray([]);
self.caseId = caseId;
self.selectedPin.subscribe(function (newValue) {
console.log(newValue);
//addCaseToPin(newValue, self.caseId);
});
}
var pinObjs = [];
$(function () {
pinObjs = [];
$(".pinBinding").each(function () {
var caseId = this.getAttribute("data-caseid");
var view = new UserPinViewModel(caseId);
pinObjs.push(view);
ko.cleanNode(this);
ko.applyBindings(view, this);
});
})
The userPins array is populated by an AJAX call to the server as the values in the dropdown are dependent upon another section of the website which can change the values in the dropdown - here the logic I have used to populate the array.
function getPins() {
$.ajax({
type: 'POST',
url: '/Home/GetPins',
success: function (data) {
for (var i = 0; i < pinObjs.length; i++) {
pinObjs[i].userPins(data);
}
},
error: function (request, status, error) {
alert("Oooopppppsss! Something went wrong - " + error);
}
});
}
The actual values in the dropdowns all change to match what is returned from the server however whenever I manually change the dropdown, the subscription event is not fired.
You're using both jQuery and Knockout to manipulate the DOM, which is not a good idea. The whole idea of Knockout is that you don't manipulate the DOM, it does. You manipulate your viewModel.
Using cleanNode is also a code smell, indicating that you're doing things the wrong way. Knockout will handle that if you use the tools Knockout provides.
In this case, I was going to suggest a custom binding handler, but it looks like all you really want is to have a UserPinViewModel object created and applied to each instance of your .pinBinding element in the HTML. You can do that using the with binding, if you expose the UserPinViewModel constructor in your viewModel.
function UserPinViewModel(caseId) {
var self = this;
self.selectedPin = ko.observable();
self.userPins = ko.observableArray([]);
self.caseId = caseId;
self.selectedPin.subscribe(function(newValue) {
console.log(newValue);
//addCaseToPin(newValue, self.caseId);
});
// Pretend Ajax call to set pins
setTimeout(() => {
self.userPins([{
Name: 'option1',
Id: 1
}, {
Name: 'option2',
Id: 2
}, {
Name: 'option3',
Id: 3
}])
}, 800);
// Later, the options change
setTimeout(() => {
self.userPins([{
Name: 'animal1',
Id: 'Elephant'
}, {
Name: 'animal2',
Id: 'Pony'
}, {
Name: 'animal3',
Id: 'Donkey'
}])
}, 4000);
}
ko.bindingHandlers.pin = {
init: () => null,
update: () => null
};
ko.applyBindings({
pinVm: UserPinViewModel
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div id="case-pin-#modelItem.CaseID" data-bind="with: new pinVm('someCaseId')" class="row hidden popovercontainer pinBinding">
<select data-bind="options:userPins,
value:selectedPin,
optionsCaption:'-- please select --',
optionsText: 'Name',
optionsValue: 'Id'"></select>
</div>
Your getPins function suggests that the .pinBinding elements should correspond to the data being received. In that case, pinObjs should really be a part of your viewModel, and the elements should be generated (perhaps in a foreach) from the data, rather than being hard-coded. I don't know how that works with what I presume is the server-side #modelItem.CaseID, though.
I have a form working with JQuery Autocomplete and it works fairly well. Now I need another element to force a user to select a valid choice in the autocomplete input. The can type whatever they want and everything is filtered by autocomplete. But they have to select something from the served list.
If they don't the inputfield must get blanked. Tried out a few things with change and select to no avail. This is the code of my autocomplete. I saw some examples operation with data instead of source. This seems to make a big difference
$(function () {
$("#sp_name").autocomplete({
minLength: 2,
delay: 300,
source: function (request, response) {
$.ajax({
url: "./Search/",
dataType: "json",
data: {
term: request.term,
zoekterm: $("#al").html()
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.naam,
value: item.naam
}
}));
}
});
}
})
});
Try this:
I am using a local list here, but you can achieve this via json data source too.
Just add a change event. The only problem this can have is that if user does not click on
the suggestion, it will turn blank (even if user is entering the same text as suggestion).
It will be mandatory for user to click on the suggestion.
var list = ["c", "c++", "c#","Basic","Mongo"];
$('#auto').autocomplete({
source: list,
select: function (event, ui) {
$(this).val(ui.item ? ui.item : " ");},
change: function (event, ui) {
if (!ui.item) {
this.value = '';}
//else { Return your label here }
}
});
JsFidle for it: http://jsfiddle.net/sarcastic/7KdZP/112/
In your case, Change function would be something like this:
change: function (event, ui)
{
if (!ui.label) { this.value = ''; }
}