How to validate Kendo Dropdownlist using jQuery validate - kendo-ui

I have normal razor as well as kendo controls in my form, i am facing some problem while trying to validate kendo dropdownlist using jquery validate plugin.
The below is my code.
#(Html.Kendo().DropDownList()
.Name("color")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>() {
new SelectListItem() {
Text = "Select Value",
Value = ""
}, new SelectListItem() {
Text = "Black",
Value = "2"
},
new SelectListItem() {
Text = "Orange",
Value = "3"
},
new SelectListItem() {
Text = "Grey",
Value = "4"
}
}).Value("")
.HtmlAttributes(new { style = "width: 100%" })
)
<input type="submit" value="Submit" />
now i have used my jquery validate like this
$(document).ready(function () {
$("#dropDownForm").validate({
rules: {
color: "required"
},
highlight: function (element) {
alert('highlight');
},
unhighlight: function (element) {
alert('unhighlight');
},
errorPlacement: function (error, element) {
return false;
},
debug: true
});
});
but i am not able to validate the dropdown list and both highlight and unhighlight event of jquery validate plugin is not getting called.
Any help is appreciated.
Thank you

Following is recommended
Put $.validator.setDefaults({ ignore: '' }); not inside $(document).ready
jQuery Validate - Enable validation for hidden fields
http://www.telerik.com/forums/mvc-client-validation-not-working

Related

How create confirmation popup in kendo UI?

I have jquery UI code for confirm popup.
if (confirm('Are you sure you want to delete the batchjob:' +
dataItem["Name"])) {
$.get("#Url.Content("~/BatchJob/DeleteBatchJob")", { batchJobDetailId: parseInt(dataItem["BatchJobDetailId"]) }, function (data) {
if (data) {
debugger
var batchJobValidateWnd = $("#ValidateBatchJobStatus").data("kendoWindow");
batchJobValidateWnd.content("BatchJob deleted successfully.");
batchJobValidateWnd.center().open();
$.post("#Url.Content("~/BatchJob/SearchBatchJobDetailByParams")", { jobName: $("#Name").val(), startDate: $("#ScheduleStartDate").val() }, function (data) {
});
}
else {
debugger
window.location = '#Url.Content("~/BatchJob/Create")/' + parseInt(dataItem["BatchJobDetailId"]);
}
});
}
And I need Kendo Confirmation popup?How i change jquery confirm popup to kendo confirm popup
You can create a Kendo Confirmation Dialog via a promise, and if confirmed execute the same way as you would with a jQuery dialog.
The dialog itself should be created using an External Template which is rendered on buttonDisplayDialog click event which will wait for a response before continuing.
<script id="confirmationTemplate" type="text/x-kendo-template">
<div class="popupMessage"></div>
</br>
<hr/>
<div class="dialog_buttons">
<input type="button" class="confirm_yes k-button" value="Yes" style="width: 70px" />
<input type="button" class="confirm_no k-button" value="No" style="width: 70px" />
</div>
</script>
Based on whether the user clicks "Yes" or "No" will return result as a true or false value which is where you should put the remainder of your code:
$("#buttonDisplayDialog").kendoButton({
click: function(e) {
$.when(showConfirmationWindow('Are you sure you want to delete the batchjob:')).then(function(confirmed){
if(confirmed){
alert('This is where you will put confirmation code');
}
else{
alert('User clicked no');
}
});
}
});
});
function showConfirmationWindow(message) {
return showWindow('#confirmationTemplate', message)
};
function showWindow(template, message) {
var dfd = new jQuery.Deferred();
var result = false;
$("<div id='popupWindow'></div>")
.appendTo("body")
.kendoWindow({
width: "200px",
modal: true,
title: "",
modal: true,
visible: false,
close: function (e) {
this.destroy();
dfd.resolve(result);
}
}).data('kendoWindow').content($(template).html()).center().open();
$('.popupMessage').html(message);
$('#popupWindow .confirm_yes').val('OK');
$('#popupWindow .confirm_no').val('Cancel');
$('#popupWindow .confirm_no').click(function () {
$('#popupWindow').data('kendoWindow').close();
});
$('#popupWindow .confirm_yes').click(function () {
result = true;
$('#popupWindow').data('kendoWindow').close();
});
return dfd.promise();
};
Here is a Dojo example to demonstrate the above code in action.

Kendo Server Side Grid: Custom Buttons

What is the correct way to bind custom buttons (class glyphicons) to Kendo columns / toolbars?
.ToolBar(tb =>
{
tb.Template("<button type=button id=gridTrainerAdd><span class='glyphicon glyphicon-plus-sign'></span></button>");
})
works but icon looks quite differen than expected (probalby nested css problem).
How do I use buttons in columns? During researches I only found quite different solutions for client side grids...
What would this (compare columns button "View details") be in server side (fluent) notation?:
$(function () {
var grid = $("#grid").kendoGrid({
dataSource: {
pageSize: 20,
data: createRandomData(50)
},
sortable: true,
columnMenu: true,
pageable: true,
height: 430,
columns: [
{ field: "FirstName", title: "First Name", width: "140px" },
{ field: "LastName", title: "Last Name", width: "140px" },
{ field: "Title" },
{ command: {
text: " View Details",
click: showDetails,
className: "fa fa-map-marker"
},
title: " ",
width: "140px"
}],
dataBound: function (e) {
e.sender.tbody.find(".k-button.fa").each(function(idx, element){
$(element).removeClass("fa fa-map-marker").find("span").addClass("fa fa-map-marker");
});
}
}).data("kendoGrid");
I'd expect somthing like:
columns.Command(com => com.Custom());
Try adding k-button and k-button-icontext classes to your button. It will give the button the kendo theme styling.
tb.Template("<div class='toolbar'><a class='k-button k-button-icontext k-grid-add' href=''><span class='glyphicon glyphicon-plus-sign'></span>add</a></div>");
Update:
You can add custom css to the button in MVC with the HtmlAttributes method.
columns.Command(command =>
{
command.Edit();
command.Destroy();
command.Custom("Copy").Click("CopyPOLine").HtmlAttributes(new { #class = "k-copy-icon"});
}).Width(175);
Update2:
Also you should check out the custom command demo on the kendo ui website. Here is part of the example copied below.
#(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.EmployeeViewModel>()
.Name("Grid")
.Columns(columns => {
columns.Bound(e => e.FirstName).Width(140);
columns.Bound(e => e.LastName).Width(140);
columns.Bound(e => e.Title);
columns.Command(command => command.Custom("ViewDetails").Click("showDetails")).Width(180);
})
.HtmlAttributes(new { style = "height: 400px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("CustomCommand_Read", "Grid"))
)
)
<script type="text/javascript">
var detailsTemplate = kendo.template($("#template").html());
function showDetails(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var wnd = $("#Details").data("kendoWindow");
wnd.content(detailsTemplate(dataItem));
wnd.center().open();
}
</script>

Option of Dropdown is not display in kendo grid popup template

I try to create dropdown into kendo grid edit popup tempate.but i unable to get value of dropdown into popup tempate.how to get it using kendo grid popup?
kendo field detail is describe below
{ field: "PaymentMode", title: "Payment Mode", width: 150, editor: paymentModeDropDownEditor, template: "#:AvailablePaymentMode#", hidden: true },
At Edit Event code is written below
edit: function (e) {
var formTypeData = new kendo.data.DataSource({
data: [
{ Text: "Cheque", Value: "0" },
{ Text: "Cash", Value: "1" },
]
});
function paymentModeDropDownEditor(container, options) {
$('<input required data-text-field="Text" id="paymentMode" data-value-field="Value" data-bind="value:PaymentMode"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: true,
dataSource: formTypeData,
change: onChange,
});
}
function onChange(e) {
var dataItem = this.dataItem(e.item);
if (dataItem.Text == "Cash") {
$("input[name='ChequeReferenceNo']").hide();
$("label[for='ChequeReferenceNo']").hide();
$("input[name='BankName']").hide();
$("label[for='BankName']").hide();
}
else {
$("input[name='ChequeReferenceNo']").show();
$("label[for='ChequeReferenceNo']").show();
$("input[name='BankName']").show();
$("label[for='BankName']").show();
}
};
Kendo grid popup template script is written below
<script id="InvoiceUpdatePopup_editor" type="text/x-kendo-template">
<input name="paymentMode" data-bind="value:AvailablePaymentMode" data-value-field="value" data-text-field="text" data-role="dropdownlist" />
<script>
I know its not as per your query but have implemented using editable template as below:
Grid --
Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("PopupEditView"))
Grid Model :-
.Model(model =>
{
model.Id(p => p.ID);
model.Field(p => p.Role).DefaultValue(ViewData["defaultCategory"] as UserRole);
}
PopupEditView-
#(Html.Kendo().DropDownListFor(model => model.Role)
.DataValueField("Id")
.DataTextField("RoleName")
.SelectedIndex(Model.Role.Id)
//.Value(Model.Role.RoleName)
//.Events(e => e.("onDataBound"))
.BindTo(ViewData["Category"] as IEnumerable<UserRole>)
.HtmlAttributes(new { style = "width: 280px;" })
)
Controller--
ViewData["Category"] = list;
ViewData["defaultCategory"] = list.FirstOrDefault();
let me know how it worked for you.

How to programatically expand a node of Kendo treeview

I have a Kendo treeview that is built as below codes (see below). Each tree node has a unique data id field (that is employee Id).
I would like to have a text box ( <input type="text" ... /> ) and a button ( <input type="button" ... /> ) so user can input some id and when she hit the button, the button click event handler will let the treeview expand the node whose id matches the input id. How can I do that? Thank you very much.
Details of click event handler or the button:
function buttonExpand_onClick()
{
var id = $("textboxEmployeeId").val();
// ???
// how can I do the following code lines to expand the node with id of "id" to see all its children?
}
Details of the existing Kendo treeview building codes:
<div id="treeviewEmployee">
</div>
<script id="treeview-template" type="text/kendo-ui-template">
#: item.text #
</script>
$(function(
{
var defaultRootSelectedId = 1; // 1 is employee id of the root employee on first loading
$.ajax({
url: '/Employee/AjaxGetEmployeeNodes/?id=' + defaultRootSelectedId,
type: 'GET',
dataType: 'json',
async: false,
success: function (data, textStatus, xhr) {
$("#reeviewEmployee").kendoTreeView({
template: kendo.template($("#treeview-template").html()),
dataSource: data,
select: treeview_onSelect
});
_treeview = $("#treeviewEmployee").data("kendoTreeView");
},
error:
function (xhr, textStatus, errorThrown) {
alert(textStatus);
}
});
});
You can access the datasource on the treeview and find the node by id. I would also like to add that the treeView has a 'findByText()' method as well, in case that is what you want.
HTML
<script id="treeTemplate" type="text/x-kendo-template">
#: item.text #
</script>
<div id="content">
<div id="form">
<label>Node ID:
<input id="nodeId" type="text"/>
</label>
<button id="expandNodeBtn">Expand Node</button>
</div>
<h2>TreeView</h2>
<div id="treeView"/>
</div>
JAVASCRIPT
(function ($) {
$(document).ready(function () {
$("#treeView").kendoTreeView({
dataSource: [
{
text: 'one with id 1',
id: 1,
items: [
{
text: 'one-child-1',
id: 2
},
{
text: 'one-child-2',
id: 3
}
]
},
{
text: 'two with id 4',
id: 4,
items: [
{
text: 'two-child-1',
id: 5
},
{
text: 'two-child-2',
id: 6
}
]
}
]
});
$("#expandNodeBtn").on("click", function(e) {
var val = $("#nodeId").val();
console.log('val: ' + val);
var treeView = $("#treeView").data('kendoTreeView');
var dataSource = treeView.dataSource;
var dataItem = dataSource.get(val); // find item with id = 5
var node = treeView.findByUid(dataItem.uid);
treeView.expand(node);
});
});
})(jQuery);
JSFiddle
I also put together a JSFiddle sample for you to play with: http://jsfiddle.net/jsonsee/D35Q6/
Slightly related, but I came here looking for an answer to this question: How to expand the whole branch when clicking to a parent node in angular treeview? Since I didnt find any answers, I post my solution here. Hope it helps someone.
html
<div id="treeview" kendo-tree-view="tree" k-options="options" k-on-change="selectItem(dataItem)">
</div>
controller
$scope.options = {
dataSource: dummyData,
template: $scope.treeItemTemplate
}
$scope.treeItemTemplate = "<button ng-click='expandRoot(dataItem)'>Blow up</button>";
$scope.expandRoot = function expandRoot(dataItem) {
dataItem.expanded = true;
if (dataItem.hasChildren) {
dataItem.load()
var children = dataItem.children.data();
children.forEach(function (c) {
c.expanded = true;
$scope.expandRoot(c)
});
}
}

How to hide the expand/collapse icon for the detail grid in kendo ui

I am using kendo ui grid detail Template. In the grid i have a dropdown with some values like dropdown, textbox etc. If i add the new record then i don't want to show the expand/collapse icon. After selecting the dropdown and the selected value will be dropdown then only i want to show the expand/collapse icon. How can i able to do this using kendo ui. Hope you understand my quesion.
I have tried to access that in the dataBound Event like this
dataBound: function (e) {
var dataSource = this.dataSource;
this.element.find('tr.k-master-row').each(function() {
this.tbody.find("tr.k-master-row>.k-hierarchy-cell>a").hide();
});
}
Try this:
function dataBound() {
var grid = this;
//expand all detail rows
grid.tbody.find("tr.k-master-row").each(function () {
grid.expandRow($(this));
})
//remove hierarchy cells and column
$(".k-hierarchy-cell").remove();
$(".k-hierarchy-col").remove();
}
Another option is to set the Width() to look like it's hidden.
function dataBound() {
$(".k-hierarchy-cell", "#gridName").width(0.1);
$(".k-hierarchy-col", "#gridName").width(0.1);
}
If you use Kendo's MVC helper, it' way easier to do this that way:
$(".k-hierarchy-cell").hide();
$(".k-hierarchy-col").remove();
It hides first default column (with icon) but in the same time it keeps other columns in right position.
if you wonder how to do it with React without using jQuery, I ended up using cellRender props.
....
const cellRender = (tdElement, cellProps) => {
if (cellProps.field === 'expanded') { // this is the expand column you want to hide
if (cellProps.dataItem.ProductName !== 'Chai') { // Condition goes here. I disabled all expand icon if ProductName is not Chai
return <td> </td>;
}
}
return tdElement;
};
return (
<Grid
...
cellRender={cellRender}
...
>
<Column field="ProductName" title="Product" width="300px" />
<Column field="ProductID" title="ID" width="50px" />
<Column field="UnitPrice" title="Unit Price" width="100px" />
<Column field="QuantityPerUnit" title="Qty Per Unit" />
</Grid>
);```
To conditionally show the grid row details arrow, add a databound event to your grid that has the detail template. In the databound event, call this function:
dataBound: function (e) { // on data bound
var items = e.sender.items(); // find all rows
items.each(function() { // for each row
var row = $(this); //
var dataItem = e.sender.dataItem(row); // get the data item of the row
if (!dataItem.HasChildren) { // check for children
row.find(".k-hierarchy-cell").html(""); // if no children, hide arrow
}
});
}
<div id="example">
<div id="grid"></div>
<script type="text/x-kendo-template" id="template">
some content
</script>
<script>
$(document).ready(function() {
var element = $("#grid").kendoGrid({
dataSource: [
{FirstName: "name1", hasChildren: true},
{FirstName: "name2", hasChildren: false}
],
height: 550,
sortable: true,
pageable: false,
detailTemplate: kendo.template($("#template").html()),
detailInit: detailInit,
dataBound: function(e) {
var items = e.sender.items();
items.each(function(){
var row = $(this);
var dataItem = e.sender.dataItem(row);
if(!dataItem.hasChildren){
row.find(".k-hierarchy-cell").html(""); //It will hide
}
})
},
columns: [
{
field: "FirstName",
title: "First Name",
width: "120px"
}
]
});
});
function detailInit(e) {
}
</script>
</div>

Resources