Kendo MVVM Dropdown - How to set initial value based on other data? - kendo-ui

I have the following html for a Kendo MVVM DropDownList:
<select id="responseTypeDDL"
data-role="dropdownlist"
data-text-field="SystemResponseTypeCode"
data-value-field="SystemResponseTypeId"
data-bind="value: selectedSystemResponseTypeCode, source: responseTypes">
</select>
This is my view model:
SC.ViewModels.Reference.ResponseTypeDataSource.read();
var responseTypeDDL = kendo.observable({
responseTypes: SC.ViewModels.Reference.ResponseTypeDataSource,
selectedSystemResponseTypeCode: null,
setSelectedSystemResponseTypeCode: function (code) {
this.selectedSystemResponseTypeCode = code;
},
});
kendo.bind($("#responseTypeDDL"), responseTypeDDL);
// after reading data, I call the method to set the selected value like this:
self.ResponseTypeDDL.setSelectedSystemResponseTypeCode(results.code);
The ResponseTypeDataSource.read() method returns a list of "XML", "JSON". This is the SystemResponseTypeCode field. I also read another data item from the database
and check its response type. Let's say it is "JSON". How do I set the drop down to have "JSON" selected?

First of all this part seems to be wrong
setSelectedSystemResponseTypeCode: function (code) {
this.selectedSystemResponseTypeCode = code;
},
You should make sure to call set() method while modifying an observed variable, otherwise it might not update the bindings:
this.set("selectedSystemResponseTypeCode", code);
And for your actual question
You need to set data-value-primitive="true" in order to work with just the id (Kendo Docs) (Please note changes below, value: selectedSystemResponseTypeId)
<select id="responseTypeDDL"
data-role="dropdownlist"
data-text-field="SystemResponseTypeCode"
data-value-field="SystemResponseTypeId"
data-value-primitive="true"
data-bind="value: selectedSystemResponseTypeId, source: responseTypes">
</select>
SC.ViewModels.Reference.ResponseTypeDataSource.read();
var responseTypeDDL = kendo.observable({
responseTypes: SC.ViewModels.Reference.ResponseTypeDataSource,
selectedSystemResponseTypeCode: null,
selectedSystemResponseTypeId: null,
setSelectedSystemResponseTypeId: function (id) {
this.set("selectedSystemResponseTypeId", id);
},
});
kendo.bind($("#responseTypeDDL"), responseTypeDDL);
// Get your id
var id = ...
responseTypeDDL.setSelectedSystemResponseTypeId(id);
Working example: http://dojo.telerik.com/AbIm/8

I've managed to manually set the value in dropdownlist without resorting to
data-value-primitive="true"
because i need to access the selected value and display other fields.
Here's the solution:
var id = 1004;
var dataItem = responseTypeDDL.responseTypes.get(id); //get the id in your datasource
responseTypeDDL.set("selectedsystemResponse", dataItem);

Related

How to pass javascript variable to velocity template

I created a dropdownlist using jqwidgets and i got a form using velocity template. In the form action i want to get the selected value of my dropdownlist. i need the value in my controller page. How can i get the selected value of the dropdownlist inside velocity template variable? I am passing the item inside $submitUrl.setParameter("filePath", "item"). but if I print the value inside controller then I am getting only item. not the selected value of the dropdownlist. Any suggession?
<script type="text/javascript">
$(document).ready(function ()
{
// Create the countryjqxWidget DropDownList
$("#countryjqxWidget").jqxDropDownList({source: countryList, selectedIndex: 0, width: '200', height: '25', theme: 'ui-redmond'});
$('#countryjqxWidget').on('change', function (event)
{
var args = event.args;
if (args) {
// index represents the item's index.
var index = args.index;
var item = args.item;
// get item's label and value.
var label = item.label;
var value = item.value;
alert(value);
var item = $("#jqxDropDownList").jqxDropDownList('getSelectedItem');
}
});
});
</script>
<form id="form" class="form-horizontal" action="$submitUrl" method="post" >
#lr_btn("submit-btn", "Submit", "Submitting...")
</form>
#set( $submitUrl = $renderResponse.createActionURL() )
$submitUrl.setParameter("submit", "upload")
$submitUrl.setParameter("filePath", "item")
Have you tried by adding the "countryjqxWidget" within your Form and setting its "name" attribute. As far as I know, if you set the "name" attribute, the selected value will be passed automatically on Form submit. It does not matter that the jQWidgets DropDownList is created from DIV tag, You can still set its "name" attribute.

grails: remoteFunction with multiple select

I need to use the remoteFunction directive with a multiple select.
The select is as follows:
<g:select name="receiptItems" from="${myproject.ReceiptItem.list()}"
multiple="multiple" optionKey="id" optionValue="description" size="5"
value="${receiptInstance?.receiptItems*.id}" class="many-to-many"
onchange="${remoteFunction(
controller: 'Receipt',
action: 'sumReceiptItems',
params: '\'receiptItemsSelected=\' + this.value',
onSuccess: 'updateTotalAmount(\'totalAmount\', data, \'00000\')')}"/>
I have the sumReceiptItems action in the Receipt controller that takes the parameter receiptItemsSelected and use it to update another text field.
The problem is that this.value gives me only one selected value, that is the last one selected. I need to pass to controller all the selected values in the select.
How can I do it?
Thanks for your precious help
Just use jQuery's val() instead of this.value, that will get all the selected items:
params: '\'receiptItemsSelected=\' + jQuery(this).val()'
Note that you have to import jQuery if you haven't used it in your project yet. You can do that simply using <r:require module='jquery' /> in the <head> section if you are using an up-to-date Grails version.
You can use JQuery to get the values:
var selections = new Array();
$("#receiptItems").change(function() {
var value = $(this).val();
selections[selections.length] = value;
});
You can add the value to a global defined list. In this way you get all the selections.

How to retrieve value of a kendoAutocomplete textbox without using id, $(element) and only using custom bindings

I have the following code:
// KendoAutocomplete textbox
<input id="search" data-bind="kendo: 'kendoAutoComplete', source:searchSource" />
// For now
var autoComplete = $("#search").kendoAutoComplete();
var x= autoComplete.data("kendoAutoComplete").value();
How can I retrieve the value for x using custom binding without using id?
Your question is a little bit confusing. Lets see if I guess what you mean by "retrieve the value for x using custom binding".
Problem statement: Define a KendoUI AutoComplete that when enter a value automatically updates an ObservableObject so I can get the value without having to use autoComplete.data("kendoAutoComplete").value();
Start defining the input as:
<input id="search" data-role="autocomplete" data-bind="source: searchSource, value: x"/>
Where I define what is the datasource for autocomplete element (searchSource) plus, where to store that introduced value (x).
Then, in JavaScript I do:
var ds = new kendo.data.DataSource({
data: [ "option1", "option2", "option3" ]
});
var obj = kendo.observable({ searchSource: ds, x: "option2" });
kendo.bind("body",obj);
Where ds is the DataSource containing the values for the autocomplete and it is bound to the body of your HTML element (or whatever portion of your document).
Whenever I want to get the value introduced in the autocomplete I simple use obj.x.
You can even get an HTML div magically updated doing:
<div data-bind="html: x"></div>
See running example here: http://jsfiddle.net/OnaBai/twznn/

Is there a way to use AJAX on a DropDownList changed event to dynamically modify a partial view on a page?

Is there a way to use AJAX on a DropDownList changed event to dynamically modify a partial view on a page?
My main page has a DropDownList (DropDownListFor) and a partial view which ONLY contains a list of "items". The items shown in this partial view are dependent upon the item selected in the DropDownList. There's a 1 to many relationship between the DropDownList item and the items in the partial view. So, when the user changes the value of the DropDownList, the content in the partial view will dynamically change to reflect the item selected in the DropDownList.
Here's my DropDownList:
<div data-role="fieldcontain">
Choose Capsule:<br />
#Html.DropDownListFor(x => x.CapsuleFK, new SelectList(Model.Capsules, "pk", "name", "pk"), new { id = "ddlCapsules" })
<br />
</div>
Here's my Partial View declaration on the same page:
<div data-role="fieldcontain">
#Html.Partial("_FillerPartial", Model.Fillers)
</div>
I'm not very familiar with Ajax, but looking at other examples, here's what I have for my Ajax:
$(document).ready(function () {
$('#ddlCapsules').change(function () {
// make ajax call to modify the filler list partial view
var selection = $('#ddlCapsules').val();
var dataToSend = { cappk: selection };
$.ajax({
url: 'Process/GetFillersByCapsule',
data: { cappk: dataToSend },
success: function (data) {
alert("server returned: " + data);
}
});
});
});
And finally, here's a screenshot of what's going on. By changing the "Choose Capsule" drop down list, I want the Filler list to update dynamically:
You can load the drop down list as a partial view from the controller using ajax.
The controller code:
[HttpGet]
public virtual ActionResult GetFillersByCapsule(string cappk)
{
var model = //Method to get capsules by pk, this returns a ViewModel that is used to render the filtered list.
return PartialView("PartialViewName", model);
}
The main view html:
<div id="filteredList">
</div >
The partial view
#model IEnumerable<MyCapsuleModel>
foreach (var x in Model)
{
//Render the appropriate filtered list html.
}
And you can load the filtered list using ajax:
$('#ddlCapsules').change(function () {
// make ajax call to modify the filler list partial view
var selection = $('#ddlCapsules').val();
var dataToSend = { cappk: selection };
$.ajax({
url: 'Process/GetFillersByCapsule',
data: { cappk: dataToSend },
success: function (data) {
$("#filteredList").empty();
$("#filteredList").html(data);
}
});
});
Hope this helps.
You can't update the partial, per se, because the partial will never be rendered again without a page reload. Once you receive the HTML, ASP is done, you're on your own at that point.
What you can do, of course, is switch out the content of a particular div or whatever using JavaScript. Your example in particular screams Knockout, so that's what I would recommend using.
Change your HTML to add a data-bind to your containing div:
<div data-role="fieldcontain" data-bind="foreach: filler">
<button data-bind="text: name"></button>
</div>
And your DropDownList:
#Html.DropDownListFor(x => x.CapsuleFK, new SelectList(Model.Capsules, "pk", "name", "pk"), new { id = "ddlCapsules", data_bind = "event: { change: updateFillers }" })
Then, some JavaScript:
var FillersViewModel = function () {
var self = this;
self.fillers = ko.observableArray([]);
self.updateFillers = function () {
var selection = $('#ddlCapsules').val();
var dataToSend = { cappk: selection };
$.ajax({
url: 'Process/GetFillersByCapsule',
data: { cappk: dataToSend },
success: function (data) {
self.fillers(data.fillers) // where `fillers` is an array
}
});
}
}
var viewModel = new FillersViewModel();
ko.applyBindings(viewModel);
This is a very simplistic example, and you'll need to do some more work to make it do everything you need it to do in your scenario, but the general idea is that every time the dropdown list is changed, Knockout will call your updateFillers method, which will execute the AJAX and put new data into the fillers observable array. Knockout automatically tracks changes to this array (hence the "observable" part), so an update is automatically triggered to any part of your page that relies on it. In this scenario, that's your div containing the buttons. The foreach binding will repeat the HTML inside for each member of the array. I've used a simple button element here just to illustrate, but you would include the full HTML required to create your particular button like interface. The text binding will drop the content of name in between the opening and closing tag. Refer to: http://knockoutjs.com/documentation/introduction.html for all the binding options you have.
There's much more you could do with this. You could implement templates instead of hard-coding your HTML to be repeated in the foreach. And, you can use your partial view to control the HTML for this template. The important part is that Knockout takes the pain out of generating all this repeating HTML for you, which is why I recommend using it.
Hope that's enough to get you started.

Custom grid button to load ajax content depending on selected row

I need to make a custom buttom in my grid that will open a modal which will render a select field with options depending on selected row.
So the user will select a row and click the button. The row id should be passed as an url parameter to my action so that it can make a query and populate the select field.
This is where I'm struggling:
navigatorExtraButtons="{
honorarios:{
title: 'Consultar honorários do processo',
caption: 'H',
icon: 'none',
onclick: function(){
var id = jQuery('#processoTable').jqGrid('getGridParam','selrow');
if (id) {
var ret = jQuery('#processoTable').jqGrid('getRowData',id);
// need to pass ret.nrProcesso as param to the URL that will load content into the modal
} else { alert('Please select a row.');}
}
},
With above code I can get the desired ID value from selected row. But I don't know how to assign it to a
<s:url... param
and populate a modal...
Thanks in advance.
I've found a solution. Posting here hoping it might help someone else.
I've ended up using plain old jquery script to get the modal to show up instead of jquery-plugin.
Just construct your action url adding desired parameter and call an ajax function:
<sj:submit id="consulta_honorarios" value="Consultar Honorários" onClickTopics="honorarios" button="true"/>
<sj:dialog
id="mydialog"
title="Consultar honorários"
autoOpen="false"
modal="true"
dialogClass="ui-jqdialog"
/>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#consulta_honorarios").click(function(){
var actionURL = '<s:property value="%{advprocselecturl}" />';
var id = jQuery('#processoTable').jqGrid('getGridParam','selrow');
if (id) {
var ret = jQuery('#processoTable').jqGrid('getRowData',id);
actionURL += '?nrProcesso=' + ret.nrProcesso;
// alert('id='+ret.nrProcesso+' / actionURL='+actionURL);
jQuery.ajax({
url: actionURL
}).done(function(data){
jQuery('#mydialog').html(data).dialog('open');
});
} else {
jQuery('<div />').html('Por favor, selecione um registro.').dialog();
}
});
});
In your action you must declare a variable with the same name as your url parameter (nrProcesso in my case) with respective getter and setter.

Resources