With the new kendo multiselect how would I add options to the list and make them selected?
For instance if I have a dropdown containing: 1,2,3 and I wanted to add 4 and 5 how do I do that? Do I have to destroy the multiselect, add the options and then reinit the multiselect?
Given the following multiselect definition:
var data =
[
{ text: "Africa", value: "1" },
{ text: "Europe", value: "2" },
{ text: "Asia", value: "3" },
{ text: "North America", value: "4" },
{ text: "South America", value: "5" },
{ text: "Antarctica", value: "6" },
{ text: "Australia", value: "7" }
];
var multi = $("#select").kendoMultiSelect({
dataTextField: "text",
dataValueField: "value",
dataSource: data
}).data("kendoMultiSelect");
You can use:
var values = multi.value();
For getting the list of values.
And for setting the value to South America (element with value 5) and "Asia" (element with value 3) use:
multi.value(["5", "3"])
If you want to add values to whatever it has then you need a little trick:
var multi = $("#select").kendoMultiSelect({
dataTextField: "text",
dataValueField: "value",
dataSource: data,
value: ["1", "2", "3"]
}).data("kendoMultiSelect");
// Adding value 4 and 5 to current content
var values = multi.value().slice();
$.merge(values, ["4", "5"]);
multi.value(values);
Warning: If values 4 and 5 were already selected you will end up having them duplicated.
Just want to add some information about how to actually add new values to the multi-select.
As OnaBai points out, the code to add an item to the multi-select is
$("#SDropDown").data("kendoMultiSelect").dataSource.add({ Text: x, Value: y });
given the .cshtml
#(Html.Kendo()
.MultiSelect()
.Name("SDropDown")
.AutoBind(true)
.Placeholder("Select s...")
.DataTextField("Text")
.DataValueField("Value")
)
In order to add an item as entered in the multi-select hook the change event for the text input. Since this isn't uniquely identified, I use XPath to get the <input> element. This is hooked in document.ready (in .cshtml, so escape #):
$(document).ready(function () {
var node = document.evaluate('//select[##id="SDropDown"]/../div[contains(##class,"k-multiselect")]/input', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (node)
{
node.onkeypress = SChanged;
}
}
function SChanged(e)
{
// only append on enter
if (kendo.keys.ENTER == e.keyCode)
{
// updates multi-select data source
AddToOrganizations(this.value);
var multi = $("#SDropDown").data("kendoMultiSelect");
multi.dataSource.filter({}); //clear applied filter before setting value
// keep all currently selected items and append the user entered text
// (does not check for duplicates)
// Also, the new values can only be selected after the data source has
// been updated.
var values = multi.value().slice();
$.merge(values, [this.value]);
multi.value(values);
}
}
Related
I have a Kendo Grid where the COR ABA No. may or may not be editable, depending on a value in the first column. So, if NOC Code=='C01', then COR ABA No. is editable, otherwise it is not.
I have achieved this by adding the Edit event on the columns and in that edit handler disabling the HTML input Kendo creates, when no editing is allowed. (In the grid definition, I have Editable(true) to start). I want instead to do this by doing the logic check in the DataBound event for the grid. That is, after all data is bound, iterate over the data, determine when the column should NOT be editable, and prevent this somehow. My idea is to simply remove the click handler that I ASSUME Kendo adds for a cell when using Editable(true) as stated above. Is this the way? Or how? Thanks!
I suggest another way, instead call closeCell() on edit event, if you do not want to allow the user to edit the cell. In doing so, the cell will not display an input when the user clicks it to edit it.
<div id="grid"></div>
<script>
$("#grid").kendoGrid({
columns: [
{ field: "id" },
{ field: "name" },
{ field: "age" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30 },
{ id: 2, name: "John Doe", age: 33 }
],
schema: {
model: {
id: "id",
fields: {
"id": { type: "number" }
}
}
}
},
editable: "incell",
toolbar:["create"],
edit: function(e) {
if (!e.model.isNew() && e.container.index() == 0) {
var grid = $("#grid").data("kendoGrid");
grid.closeCell();
}
}
});
</script>
This question already has answers here:
Gray out a row in kendo grid based on column value
(2 answers)
Closed 6 years ago.
I have a Kendo Grid whose values get populated based on a post call. I need to gray out an entire row if one of the column has a value "REGISTERED".
Is there a way we can achieve this?
Here is my code:
$("#grid").kendoGrid({
columns: [
{ field: "name", title: "Release Name" },
{ field: "number", title: "Number" },
{ field: "status", title: "Registration Status" }
],
dataSource: [
{ name: "Jane Doe", number: "50", status: "REGISTERED" },
{ name: "John Doe", number: "60", status: "NOT REGISTERED" }
]
});
If you want to change the style of a kendo grid element, you should do it on the dataBound event. When this event will be fired, all the view element will be rendered and you'll be able to retrieve a specific DOM element based on the dataItem's uid.
$("#YourGrid").kendoGrid({
dataBound: function() {
$.each($("#YourGrid").data("kendoGrid").dataSource.view(), function (index, viewDataItem) {
var row = $("#YourGrid").find("tbody>tr[data-uid='" + viewDataItem.uid + "']");
if (viewDataItem.status == "REGISTERED") {
row.css("background-color", "red"); //Use row.find("td") if you want to set the style at the cell level
} else {
row.css("background-color", "");
}
});
}
});
just check this fiddle link
I have created demo grid example using kendo's dataSource
Fiddle Link For Kendo Grid Row Background Color
Hope This May Help You.
I have a kendo combo box with two entries, say "Thing 1" and "Thing 2". I want "Thing 1" to be set by default.
Is there a preferred way to do this? I can't seem to find it, although I did set the placeholder attribute to "Thing 1" and it worked. The Kendo documentation says that placeholder is "The hint displayed by the widget when it is empty. Not set by default." Am I using placeholder incorrectly?
The optionLabel attribute (which I believe you refer to as the placeholder) is used to specify the text representing no selection. When that is chosen from the list, the selected item is null so is not the correct solution for setting a default, unless you wish the default selection to be null. The selection can be set programmatically by calling the select() method on the widget instance. The following for example will set the selection to 'Thing1'.
<div id="dropdownlist"></div>
<script type="text/javascript">
$("#dropdownlist").kendoDropDownList({
dataSource: [
'Thing1',
'Thing2',
'Thing3'
],
optionLabel: "None"
});
$("#dropdownlist").data("kendoDropDownList").select(1);
</script>
It is worth noting that this is not the only way to achieve this. My above example uses Imperative(JQuery) syntax to declare the dropdown. If you are using the ASP.NET MVC server wrappers, there is a Value attribute you can set in the declaration, for example:
.Value("1")
Finally, if you are using MVVM with declarative initialization, you can bind the selection to a value on a View Model. I haven't complicated my answer with an MVVM example since I assume you aren't using this mechanism.
<script>
$(function () {
var data = [
{ text: "12 Angry Men", value: "1" },
{ text: "Il buono, il brutto, il cattivo.", value: "2" },
{ text: "Inception", value: "3" },
{ text: "One Flew Over the Cuckoo's Nest", value: "4" },
{ text: "Pulp Fiction", value: "5" },
{ text: "Schindler's List", value: "6" },
{ text: "The Dark Knight", value: "7" },
{ text: "The Godfather", value: "8" },
{ text: "The Godfather: Part II", value: "9" },
{ text: "The Shawshank Redemption", value: "10" },
{ text: "The Shawshank Redemption 2", value: "11" }
];
$("#movies").kendoComboBox({
dataTextField: "text",
dataValueField: "value",
dataSource: data,
});
let combobox = $("#movies").data("kendoComboBox");//This "instantiates it"
combobox.value("The Godfather");
});
</script>
<input id="movies" />
Result:
How can I configure free-jqGrid (4.8) filterToolbar to search all word within a field?
Data
one two three
two three four
one four three
Search Words
"one four" , returns row 3
"four three" , returns rows 2 and 3
"one three" , returns rows 1 and 3
"four" , returns rows 2 and 3
jqGrid API
$("#list").jqGrid({
datatype: "local",
colNames: ["Name"],
colModel: [{
name: "name",
index: "name"
}],
caption: "Viz Test",
pager: '#pager',
search: true,
multiselect: true,
data: myData
});
jQuery("#list").jqGrid('filterToolbar', {
searchOperators: true
});
This is based on this answer and requires free-jqgrid 4.8 and see demo on jsfiddle
colModel: [{
name: "name",
index: "name",
searchoptions: {
sopt: ["sIn", "bw", "cn", "lt", "le", "gt", "ge", "in", "ni"]
}
}],
customSortOperations: {
// the properties of customSortOperations defines new operations
// used in postData.filters.rules items as op peroperty
sIn: {
operand: "sIn", // will be displayed in searching Toolbar
text: "String In", // will be shown in Searching Dialog
// or operation menu in searching toolbar
filter: function (options) {
// called for filtering on the custom operation "sIn"
// It has the following properties:
// item - the item of data (exacly like in mydata array)
// cmName - the name of the field by which need be filtered
// searchValue - values in the input field of searching toolbar
var fieldData = options.item[options.cmName];
var words = options.searchValue.split(" ");
//loop thru each word in words array
$.each(words, function () {
//search for word in fielddata
var searchResults = fieldData.search(this)
//if not fouond
if (searchResults < 0) {
fieldData = "";
}
});
return fieldData;
}
}
Im currently working on a project which uses jqGrid with multiple subgrids. I'm trying to get the rowid (and get at the data within the row) when a row is clicked or double clicked. Eventually I would like to fill a text box with data from a clicked row.
I've tried a few variations using ondblClickRow and onSelectRow examples on here but wans't able to get it working. I think I'm missing something really simple but don't see what. So I went back and simplified it down as much as possible to just recognize the row click and display an alert. This won't work for me either.
(based on the example in jqGrid : issue loading nested sub grid with local datatype) Look for the //***************
part near the bottom..
var myData = [
// main grid data
{ id: "1", col1: "11", col2: "12",
subgrid: [
// data for subgrid for the id=m1
{ id: "1", c1: "aa", c2: "ab", c3: "ac",
subgrid: [
// data for subgrid for the id=m1, subgridId=s1a
{ id: "1", d1: "2aa", d2: "2ab", d3: "2ac" },
{ id: "2", d1: "2ba", d2: "2bb", d3: "2bc" },
{ id: "3", d1: "2ca", d2: "2cb", d3: "2cc" }
]},
{ id: "2", c1: "ba", c2: "bb", c3: "bc" },
{ id: "3", c1: "ca", c2: "cb", c3: "cc" }
]},
{ id: "2", col1: "21", col2: "22",
subgrid: [
// data for subgrid for the id=m2
{ id: "1", c1: "1xx", c2: "1xy", c3: "1xz",
subgrid: [
// data for subgrid for the id=m2, subgridId=s2a
{ id: "1", d1: "2xx", d2: "2xy", d3: "2xz" }
]}
]},
{ id: "3", col1: "31", col2: "32" }
],
removeSubgridIcon = function () {
var $this = $(this),
idPrefix = $this.jqGrid("getGridParam", "idPrefix");
$this.find(">tbody>tr.jqgrow>td.ui-sgcollapsed").filter(function () {
var rowData = $this.jqGrid("getLocalRow",
$.jgrid.stripPref(idPrefix, $(this).closest("tr.jqgrow").attr("id")));
return rowData.subgrid == null;
}).unbind("click").html("");
},
isHasSubrids = function (data) {
var l = data.length, i;
for (i = 0; i < l; i++) {
if (data[i].subgrid != null) {
return true;
}
}
return false;
},
specificGridOptions = [
{
colNames: ["Column 1", "Column 2"],
colModel: [
{ name: "col1" },
{ name: "col2" }
],
cmTemplate: { width: 200 },
sortname: "col1",
sortorder: "desc",
idPrefix: "s_",
pager: "#pager",
caption: "Demonstrate how to create subgrid from local hierarchical data"
},
{
colNames: ["Colunm1", "Colunm2", "Colunm3"],
colModel: [
{ name: "c1" },
{ name: "c2" },
{ name: "c3" }
],
cmTemplate: { width: 112 },
sortname: "c1",
sortorder: "desc"
},
{
colNames: ["Col 1", "Col 2", "Col 3"],
colModel: [
{ name: "d1" },
{ name: "d2" },
{ name: "d3" }
],
cmTemplate: { width: 90 },
sortname: "d1",
sortorder: "desc"
}
],
commonGridOptions = {
datatype: "local",
gridview: true,
rownumbers: true,
autoencode: true,
height: "100%",
//***************
onSelectRow : function ()
{
alert('test!');
},
//also tried many variation on this
ondblClickRow: function(rowid)
{
alert(rowid);
}
//***************
loadComplete: function () {
// one can use loadComplete: removeSubgridIcon, but I included
// curent implementation of loadComplete only to show how to call
// removeSubgridIcon from your loadComplete callback handler
removeSubgridIcon.call(this);
},
subGridRowExpanded: function (subgridDivId, rowId) {
var $subgrid = $("<table id='" + subgridDivId + "_t'></table>"),
subgridLevel = $(this).jqGrid("getGridParam", "subgridLevel") + 1,
parentIdPrefix = $(this).jqGrid("getGridParam", "idPrefix"),
pureRowId = $.jgrid.stripPref(parentIdPrefix, rowId),
localRowData = $(this).jqGrid("getLocalRow", pureRowId);
$subgrid.appendTo("#" + $.jgrid.jqID(subgridDivId));
$subgrid.jqGrid($.extend(true, {}, commonGridOptions, specificGridOptions [subgridLevel], {
data: localRowData.subgrid,
subGrid: isHasSubrids(localRowData.subgrid),
subgridLevel: subgridLevel,
idPrefix: rowId + "_",
rowNum: 10000 // we use this to have no pager in the subgrids
}));
}
};
$("#list").jqGrid($.extend(true, {}, commonGridOptions, specificGridOptions[0], {
data: myData,
subgridLevel: 0,
subGrid: isHasSubrids(myData)
}));
Anyone have any ideas why it won't recognize the row click/double click?
You wrote in comment that you get the data for the grid from the server. I suppose that the usage of datatype: "local" in the case is not the best choice. Look at the answer where I described the way how to do the same, but using datatype: "json".
Now I come back to your main question. I don't understand what text box (HTML input element) you want to fill and whether the input element is inside of the grid or outside of it. Nevertheless the only problem which you could probably have is the correct usage of idPrefix option of jqGrid.
It's very important to understand, that jqGrid use HTML <table> for representing of the body of grids. Every <tr> element of the <table> must have id attribute in the current implementation of jqGrid. So the id property from the input data will be used to assign the value of id attribute of <tr> elements. If one has more as one grid on the page or if one has grid with subgrids it's very easy to receive id duplicates which not allowed in all versions of HTML or XHTML.
Additional potential problem is the usage of numbers as id values. The most databases support auto-incremental datatype which is very practical as the key of the tables. In the case the native id (the key) for the database table and for the grid rows will be integer numbers. On the other side there are some additional restrictions depend on the version of HTML/XHTML which one uses. For example HTML5 specification says (see here)
The value must be unique amongst all the IDs in the element's home
subtree and must contain at least one character. The value must not
contain any space characters.
So even though the most web browsers allows to use numbers as the values of id attribute it's not permitted and one can get compatibility problems in case of usage of this.
To solve all the described above problem jqGrid supports idPrefix options (which was introduced by the way based on my suggestion). In the case the value of id attribute will be build as concatination of idPrefix and the id from the input data. For example in case of idPrefix: "s_" and id values "1", "2", "3" used in the main grid of the example jqGrid will assign "s_1", "s_2", "s_3" as values of id attribute of <tr> elements of the main grid. The rowid of all callbacks will be the value from id attribute ("s_1", "s_2", "s_3"). If you need get the original id you can use $.jgrid.stripPref to strip the prefix. All ids which will be sent to the server by jqGrid will be normalized ($.jgrid.stripPref will be called) by jqGrid itself.
So the code which shows how to get data onSelectRow and ondblClickRow could be the following
onSelectRow: function (rowid, stat, e) {
myDebugTrace.call(this, "onSelectRow", rowid);
},
ondblClickRow: function (rowid, iRow, iCol, e) {
myDebugTrace.call(this, "ondblClickRow", rowid);
e.stopPropagation();
},
...
where myDebugTrace function can be declared as
var myDebugTrace = function (startingText, rowid) {
var $this = $(this), p = $this.jqGrid("getGridParam"), rowData, col1,
firstCol = (p.rownumbers ? 1 : 0) + (p.subGrid ? 1 : 0);
rowData = $this.jqGrid("getRowData", rowid);
col1 = rowData[p.colModel[firstCol].name];
$("<span>" + startingText + " on " + rowid + " (original id=" +
$.jgrid.stripPref($(this).jqGrid("getGridParam", "idPrefix"), rowid) +
"). Data from the first column: \"" + col1 +"\"</span><br/>").appendTo("body");
};
The corresponding demo display the following on double-click on the row from the internal subgrid.