Simple Kendo DropDownList binding in window - kendo-ui

I have a form with a DropDownList inside a Kendo window and I want to bind existing data to it. Examples for this abound and I've done it in other situations before, but this one (which seems like it should be really easy) is escaping me because I can't seem for the life of me to get the DropDownList to show the correct value. I figure I must be missing something really simple, but I haven't done Kendo in over a year, and looking at my previous work isn't helping me either.
Extremely simplified code:
<button onclick="OnButtonClick();">Click Me</button>
<div id="form-window"></div>
<script type="text/x-kendo-template" id="form-template">
<div class="form-group">
<label for="Url">URL</label>
<input name="Url" type="text" value="#= Url #" required="required" />
</div>
<div class="form-group">
<label for="HttpVerb">HTTP verb</label>
<input name="HttpVerb" data-bind="value:HttpVerb" data-source="httpVerbsDataSource" data-value-field="verb" data-text-field="verb" data-role="dropdownlist" />
</div>
</script>
<script type="text/javascript">
var formWindow = $("#form-window")
.kendoWindow({
title: "Form",
modal: true,
visible: false,
resizable: false,
scrollable: false,
width: 500,
actions: ["Close"],
open: function () {
kendo.init($("#form-window"));
}
}).data("kendoWindow");
var formTemplate = kendo.template($("#form-template").html());
var httpVerbsDataSource = new kendo.data.DataSource({
data: [
{ verb: "GET" },
{ verb: "POST" },
{ verb: "PUT" }
]
});
function OnButtonClick(e) {
var dataItem = {
Url: "abcdef",
HttpVerb: "POST"
};
var windowContent = formTemplate(dataItem);
formWindow.content(windowContent);
formWindow.center().open();
}
</script>
When I click the button, the window opens and the form text field is populated correctly, and the DropDownList has properly been bound to the data source, but the value in my data item is not selected.
JS Bin: https://jsbin.com/wariyorilo/edit?html,js,output
What am I missing? Thanks in advance.

Related

How to get value from radio button dynamically

i am creating a form for searching a client, using either id or email both are set to be unique. Application made on Codeignitor.
I have created a form with two radio buttons, one for search with ID and another for search with mail+dob.
Depending on the radio button selected, corresponding input fields shown.
In controller, it choose the model function based on the radio button value.
This is I coded, i need to pass the value of radio button to Controller.php file
Form(only included the radio button)
$(document).ready(function() {
$("#usingdob").hide();
$("#usingmail").hide();
$("input:radio").click(function() {
if ($(this).val() == "id") {
$("#usingId").show();
$("#usingdob").hide();
$("#usingmail").hide();
} else {
$("#usingId").hide();
$("#usingdob").show();
$("#usingmail").show();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-4">
<label class="radio-inline">
<input type="radio" name="optradio" value="id" checked>Using ID </label></div>
<div class="col-md-4">
<label class="radio-inline">
<input type="radio" name="optradio" value="mail">Using DOB</label>
</div>
I expected to get the radio button value correctlyenter image description here
JS:
$('input[name="optradio"]').click(function(){
var optradio = $(this).val();
//or
var optradio = $("input[name='optradio']:checked").val();
if(optradio == 'id'){
//do your hide/show stuff
}else{
//do your hide/show stuff
}
});
//on search button press call this function
function passToController(){
var optradio = $("input[name='optradio']:checked").val();
$.ajax({
beforeSend: function () {
},
complete: function () {
},
type: "POST",
url: "<?php echo site_url('controller/cmethod'); ?>",
data: ({optradio : optradio}),
success: function (data) {
}
});
}
Try this
<script type="text/javascript">
$( document ).ready(function() {
$("#usingdob, #usingmail").hide();
$('input[name="radio"]').click(function() {
if($(this).val() == "id") {
$("#usingId").show();
$("#usingdob, #usingmail").hide();
} else {
$("#usingId").hide();
$("#usingdob, #usingmail").show();
}
});
});
</script>
One thing I noticed is that you have 'mail' as a value in the DOB option. Another is that there seems to be 3 options and yet you only have 2 radios?
I adjusted the mail value to dob and created dummy divs to test the code. It seems to work.
$(document).ready(function() {
$("#usingdob").hide();
$("#usingmail").hide();
$("input:radio").click(function() {
console.log($(this).val());
if ($(this).val() == "id") {
$("#usingId").show();
$("#usingdob").hide();
$("#usingmail").hide();
} else {
$("#usingId").hide();
$("#usingdob").show();
$("#usingmail").show();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-4">
<label class="radio-inline">
<input type="radio" name="optradio" value="id" checked>Using ID </label></div>
<div class="col-md-4">
<label class="radio-inline">
<input type="radio" name="optradio" value="dob">Using DOB</label>
</div>
<div id="usingId">
Using Id div
</div>
<div id="usingdob">
Using dob div
</div>
<div id="usingmail">
Using mail div
</div>
As far as passing the value to the controller goes, ideally the inputs should be in a form. When you submit the form, the selected value can be passed to the php.
<?php
if (isset($_POST['submit'])) {
if(isset($_POST['optradio']))
{
Radio selection is :".$_POST['optradio']; // Radio selection
}
?>
If you want to get currently checked radio button value Try below line which will return current radio button value
var radioValue = $("input[name='gender']:checked").val();
if(radioValue)
{
alert("Your are a - " + radioValue);
}

Passing data between 2 MVC widgets

I've got created a widget(combobox) with data from an external server.
I just want the value that I select from that combobox see into the label from another widget.
Source of the widget from the combobox:
<div id="exampleCombo">
<div class="demo-section k-content">
<h4>Facility</h4>
<input id="fac" style="width: 30%;" />
</div>
<script>
$(document).ready(function (user) {
$("#fac").kendoComboBox({
dataTextField: "client",
dataValueField: "client",
order: "ascending",
height: 400,
dataSource: {
// type: "odata",
type: "json",
transport: {
read: "/mvc/controllers/UserfacilitiesCombo/get/" + user
},
group: { field: "facility" }
},
});
});
Source of the widget with the label on it:
<div id="exampleLabel">
<div class="demo-section k-content">
<ul class="forms">
<li>
<label>FacilityName</label>
<input id="FacPass" name="FacPass" value="Test" class="k-textbox" style="width: 100%;" />
</li>
</ul>
</div>
Can anybody help me on this?
You can use the change event. Put this after your dataSource and add a class name to your target label
change: function(e) {
var value = this.value();
$('.yourLabelClass').html(value);
}
Here is some more info about the available events
https://docs.telerik.com/kendo-ui/api/javascript/ui/combobox/events/change

Two-way bindings with Kendo MVVM from remote data source

I want to bind JSON that I fetch from a remote source to elements on a page. I was hoping to use the Kendo DataSource to manage the transport and use MVVM to display and update the data.
I need help as I cannot work out how to display the remote data:
http://jsfiddle.net/digory/zxoLpej9/
Here is my JS:
$(function(){
var dataSource = new kendo.data.DataSource({
transport: {
read: {
//using jsfiddle echo service to simulate JSON endpoint
url: "/echo/json/",
dataType: "json",
type: "POST",
data: {
json: JSON.stringify({
"ItemA": "A",
"ItemB": "B"
})
}
}
},
schema: {
model: {
fields: {
ItemA: { type: "string" },
ItemB: { type: "string" }
}
}
}
});
var vm = kendo.observable({
source: dataSource,
foo: 42,
change: function(e) {
console.log("Changed!");
},
save: function() {
console.log("Saved!");
}
});
kendo.bind($("#my-container"), vm);
vm.source.read();
});
And here is the UI display code that I am trying to use to render the data:
<div id="my-container">
<div>
<label for="ItemA">Item A</span>
<input id="ItemA" data-bind="value: source.data.ItemA, events: { change: change }" />
</div>
<div>
<label for="ItemB">Item B</span>
<input id="ItemB" data-bind="value: source.data.ItemB, events: { change: change }" />
</div>
<div>
<label for="Foo">Foo</span>
<input id="Foo" data-bind="value: foo, events: { change: change }" />
</div>
<div>
<button data-bind="click: save, enabled: hasChanges" class="k-button k-primary">Save</button>
</div>
</div>
I've been playing around a bit more and think I might have found a suitable approach.
The key finding was to set the data in the view model from within the dataSource's change function:
http://jsfiddle.net/digory/yyunxgcw/
change: function() {
var view = this.view()[0];
vm.set("data", view);
},
I'm sure it can be more elegant, but it seems to be working!

data-bind not working in List View template within Grid detail template

I need help using a Kendo UI list view which lives within a grid row detail template.
here is something I have done so far.
<div id="grid">
</div>
<script type="text/x-kendo-template" id="gridDetailTemplate">
<div class='grid-edit'>
<div class='edit-list'></div>
</div>
</script>
<script type="text/x-kendo-template" id="editItemtemplate">
<div class='edit-Item'>
#if(Type=='string'){#
<ul><li><b>#:Name#</b></li><li><input class='inputString' value='#:DataVal()#'/></li></ul>
#}else if(Type=='number'){#
<ul><li><b>#:Name#</b></li><li><input class='inputNumber' data-role='numerictextbox' data-type='number' value='#:DataVal()#'/></li></ul>
#}else if(Type=='date'){#
<ul><li><b>#:Name#</b></li><li><input class='inputDate' data-role='datepicker' value='#:kendo.toString(DataVal(),'MM/dd/yyyy')#'/></li></ul>
#}else if(Type=='boolean'){Name #<input type='checkbox'/>
#}#
</div>
</script>
<script type="text/javascript">
$(document).ready(function () {
$.get("http://localhost:4916/DataAttribute", function (data, status) {
var selFields = new Object();
$.each(data, function (index, elem) {
selFields[elem.Name] = new Object();
selFields[elem.Name]["type"] = elem.Type;
});
$("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: { url: "http://localhost:4916/Deal",
dataType: "json"
}
},
schema: {
data: "Data", total: "Total",
model: {
fields: selFields
}
}
},
height: 430,
filterable: true,
sortable: true,
pageable: false,
detailTemplate: kendo.template($("#gridDetailTemplate").html()),
detailInit: detailInit,
columns: [{
field: "SecurityName",
title: "Security Name",
width: 250
},
{
field: "DateOfAcquisition",
title: "Date Of Acquisition",
width: 120,
format: "{0:MM/dd/yyyy}"
}, {
field: "Acres",
title: "Acres",
width: 120
}
]
});
});
});
function detailInit(e) {
$.get("http://localhost:4916/DataAttribute", function (data, status) {
var detailRow = e.detailRow;
detailRow.find(".edit-list").kendoListView({
dataSource: {
data: data,
schema: {
model: {
DataVal: function () {
switch (this.get("Type")) {
case "number"
}
if (e.data[this.get("Name")])
return e.data[this.get("Name")];
else
return '';
}
}
}
},
template: kendo.template($("#editItemtemplate").html())
});
});
}
</script>
My code gets dynamic field list and binds it to the data source for grid.
Then, in the detailInit event, I find the div within row detail and convert it into kendo UI list, for which the template have been created.
Now, when I use data-bind="value: DataVal()" ,it doesn't pick up the values of List data source. It works the way I have done i.e. value="#: DataVal() #". But, data-role does not convert the fields to specified types which are datepicker and numericinput in my case.
I believe that data-role not being used is caused due to same issue as data-bind not being read.
Can anyone help me out with this? Also, feel free to suggest any alternate ways and general code improvements. I am an ASP.NET developer and usually don't work on pure html and javascript.
PS: I would be happy to provide the context on what I am trying to achieve here if anyone is interested.
Thanks in advance.
If you can rig up a jsFiddle or jsBin example that would help debug the issue.
However, try removing the parenthesis:
data-bind="value: DataVal"
Kendo should detect that DataVal is a function and call it on its own.
I experienced a similar situation in a listview template. I created a JSFiddle to demonstrate:
http://jsfiddle.net/zacharydl/7L3SL/
Oddly, the solution is to wrap the contents of the template in a div. It looks like your template already has this, so YMMV.
<div id="example">
<div data-role="listview" data-template="template" data-bind="source: array"></div>
</div>
<script type="text/x-kendo-template" id="template">
<!--<div>-->
<div>method 1: #:field#</div>
<div>method 2: <span data-bind="text: field"></span></div>
<input data-role="datepicker" />
<!--</div>-->
</script>
var model = kendo.observable({
array: [
{ field: 'A'},
{ field: 'B'}
]
});
kendo.bind($('#example'), model);

knockout wizard + Jquery

I have a wizard contains 4 step with knockout its work fine but when i added datepicker of Jquery on step 2 date picker doesn't display (just an input type text display) if i refresh my browser it display, but i lose information of step 1 (if i refresh my browser), how can i solve my problem,
my wizard its like this: http://jsfiddle.net/FyuSD/36/
wizard.cshtml:
....
<script id="step1" type="text/html">
<div>Name: <input type="text" data-bind="value: Name"></div>
<div>Description: <input type="text" data-bind="value: Description"></div>
</script>
<script id="step2" type="text/html">
Start: <br/><input type="text" id="from" data-bind="value: StartDate">
Stop:<br/> <input type="text" id="to" class="required" data-bind="value: EndDate">
</script>
.....
DatePicker.js:
$(function () {
$("#from").datepicker({
showOn: "button",
buttonImage: "/Content/images/calendar.gif",
buttonImageOnly: true,
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1,
onSelect: function (selectedDate) {
$("#to").datepicker("option", "minDate", selectedDate);
}
});
$("#to").datepicker({
showOn: "button",
buttonImage: "/Content/images/calendar.gif",
buttonImageOnly: true,
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1,
onSelect: function (selectedDate) {
$("#from").datepicker("option", "maxDate", selectedDate);
}
});
});
I'm sorry for my bad English
thanks,
I played with the fiddle a bit and your solution is the answer to this question
jQuery UI datepicker change event not caught by KnockoutJS
Which shows a datepicker implementation for custom bindings as described in the knockout documentation: Knockout - Custom Bindings
You need to create a custom binding handler that will initialize your datepickers when the template is rendered.
// call this before you call ko.applyBindings()
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
// initialize here
},
update: function(element, valueAccessor, allBindingsAccessor) {
// change handler here
}
};
When you declare your data bindings use the name of your custom binding (instead of "value: StartDate")
<br/>
Start :<input type="text" id="from" data-bind="datepicker: StartDate, datepickerOptions: {onSelect: $root.onSelectStartDate()}" />
<br/>
End :<input type="text" id="to" data-bind="datepicker: EndDate, datepickerOptions: {onSelect: $root.onSelectEndDate()}" />
Of course $root refers to your ViewModel class so that means you need some methods there. This is where you could put your minDate and maxDate code.
function ViewModel() {
// ...
self.onSelectStartDate = function() {
return function() {
alert("Start Date selected");
};
};
self.onSelectEndDate = function() {
return function() {
alert("End Date selected");
};
};
};
I tested it in an updated fiddle here http://jsfiddle.net/carbontax/bwA4N/5/. It looks funny because the datepicker css is not available, but the binding handler is doing the right thing.

Resources