create a array of kendo multi-select selected id - javascript

i am try to create a array of selected id using kendo multi select.
here is jsfiddle
this is kendo script:-
$("#multiselect").kendoMultiSelect({
dataSource: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" }
],
dataTextField: "name",
dataValueField: "id",
select:onSelect
});
kendo select function:-
function onSelect(e){
var dataItem = this.dataSource.view()[e.item.index()];
onchng(dataItem.id);
}
create a array:-
function onchng(id){
var checkarr = [];
checkarr.push(id);
console.log(checkarr);
}
here is output is [1] [2]
but i want it ['1','2']
is it possible??
thanks

When your select event fired, 'checkarr' redefined again and again. Your problem is that. If you want values in one array, you must use a button to take values together, then push them to array in single function. Or you can use session or something like that

This is how you can do it from the Controller. Note I'm doing Request.Form, that's because for whatever reason MVC Model and Kendo UI wouldn't work together when using MultiComplete. But this will put them in an array, and this is fired off a button click like the other answer suggested.
string[] advertisers = Request.Form["Name"].ToString().Split(',');

I think that there is a much easier approach and with less side effects...
Bind change event instead of select. Why? Two reasons:
select is fired just before the element is added to the list of values so you cannot get current list and you need to add the value being selected to the values already selected.
select is not fired when you remove the selection of an option.
The code using change would be as simple as:
var multi = $("#multiselect").kendoMultiSelect({
dataSource: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" }
],
dataTextField: "name",
dataValueField: "id",
change : onSelect
}).data("kendoMultiSelect");
function onSelect(){
console.log("here", multi.value());
}
Just need to use value method from your multiselect.
Your Fiddle modified in here : http://docs.telerik.com/kendo-ui/api/framework/datasource#events-change
NOTE: change event belongs to DataSource if you need to see the documentation, check it here

Related

Datatables.js with java servlet and per row submit button

I am creating a page where I'm using DataTables.js to display information and the plan is to have a submit button on each row that submits a form with the row information.
At first I used a jstl loop to generate the table which worked but this ran into some issue with having a tag in the loop of the table to submit each row.
So now, in the servlet, I have a List that is passed from the controller and to the servlet and is the converted to a Json string using Gson. In the console, when navigating to the page, I can confirm that the the string has the correct data since I printed it out in the console.
Now my question is how do I utilize this attribute, that I do set using req.setAttribute("allX", allX) to pass it to the JSP.
I have a script tag at the bottom of the JSP to populate the table which is
<script>
$(document).ready(function () {
var allx = ${allX}
$('#allTable').DataTable({
"data" : allx
});
});
</script>
Above in the jsp I have a tag with the id allTable.
What I really need help with is correctly displaying the data in the table from the Json string and then adding a submit button to each row that submits the information in the row back to the servlet, which at this point and will probably only ever be one data point per row. I'm okay with handling the data in the servlet and processing it for use elsewhere, its just this table data, I having a huge issue with.
Not sure, if I understood your question correctly, but I assume you have no issue in collecting the data and composing the response to the client, but having issues with displaying the data in the datatables on the client side.
You would want to send an array of objects, so datatables can display it properly. Each element in that array would be an object, describing a complete row. Here is an example:
// You can use array of objects. Each object will be a row in the table.
// Compose it on the server or client side and give to DataTables for processing.
// Your objects can have many keys. You can tell DataTables which to use. In this
// example, I use allX.id and allX.type, while ignoring allX.color.
var allX = [
{ id: '0', type: 'pencil', color: 'blue' },
{ id: '1', type: 'pen', color: 'orange' },
{ id: '2', type: 'marker', color: 'black' }
];
var table = $('#allTable').DataTable({
data: allX, // allX here is our array, which contains the data to display in the table
columns: [{
data: 'id', // object key to look for value
title: 'ID' // give a title to your column
},
{
data: 'type', // our second column description
title: 'Type'
},
{
width: '30%', // our buttons column
orderable: false // we will describe it further in 'columnDefs'
},
],
"columnDefs": [{
"targets": -1, // -1 = last column
"data": null, // no data for this column, instead we will show default content, described in 'defaultContent'
"defaultContent": "<button id='submit-btn'>Submit</button> <button id='delete-btn'>Delete</button>"
}],
});
// catch a button click event
$('#allTable').on('click', 'button', function() {
// create an object from a row data
var rowData = table.row($(this).parents('tr')).data();
// fire a function, based on the button id that was clicked
if (this.id === 'submit-btn') {
submitData(rowData);
} else if (this.id === 'delete-btn') {
deleteData(rowData);
}
});
function submitData(data) {
// Process your row data and submit here.
// e.g. data === { id: '1', type: 'pen', color: 'orange' }
// Even though your table shows only selected columns, the row data
// will still contain the complete object.
// I would recommend against sending a complete object. In your case,
// with a single data point, perhaps it is fine though. However,
// always send bare minimum. For example, if you want to delete an
// entry on the server side, just send the id of the entry and let
// the server locate it and delete it by id. It doesn't need all other
// fields.
}
function deleteData(data) {
// Just an example how you can have various buttons on each row.
}

How to prevent kendo grid reload?

I have two kendo grids (A, B) ...B its loaded by clicking in A and the its data source its loaded by a property of selected row in A ..
A.accounts
dataSource: {
data: this.gridA.dataItem(this.gridA.select()),
},
My problem its that in B I have to change a property using the grid, but when the property its changed the grid its reloaded and if i have 1000 rows when I change the property in the grid (anyrow, 999 i.e), the scroll back to the beginning
...I have read and try to understand it, but a can't fix it... according to the official documentation, the row selected by
var row = this.gridApprovals.select();
var caBean = this.gridApprovals.dataItem(row);
Its a ObservableObject, so, when I try to change a property, some method (of ObservableOject) it's making this behaviour, and the grid its reloaded, its iterating every data source item...
EDITED:
I forgot to mention.. its important keep the relation between the changes of the B grid and its relation in A slection..
Here is a Dojo Project http://dojo.telerik.com/uYemI/2
How about this?
http://dojo.telerik.com/#Stephen/aNije
I removed the k-rebind attribute and instead wire up the dataSource inside your setCarsGrid() method:
$scope.setCarsGrid = function() {
var row = this.brandGrid.select();
var brand = this.brandGrid.dataItem(row);
var brandObj=brand.toJSON();
var dataSource = new kendo.data.DataSource({
data: brand.cars,
schema:{
model:{
fields:{
id:{editable:false},
model:{editable:false},
color:{type:"string"}
}
},
parse: function(response) {
$.each(response, function(idx, elem) {
elem.id = elem.id+10;
//if you put a break point here, every time you try to edit 'color' field.. will be stop because datasourse is iterated again
console.log("Grid has been reloaded and the editable field 'color' can be edited :'( the id property has been added +10")
});
return response;
}
}
});
// This first time this is called, the carsGrid has not been initialized, so it doesn't exist.
// But subsequent times, we just need to set the new datasource.
if (this.carsGrid) {
this.carsGrid.setDataSource(dataSource);
}
$scope.carsGridOptions = {
dataSource: dataSource,
selectable:true,
editable: true,
columns: [{
field: "id",
},{
field: "model",
},{
field: "color",
}]
};
}
Essentially, I am just separating initialization of the GRID from the setting of the grid's DATASOURCE.
The first time through, you set up the grid options AND set the dataSource and then subsequent times through, we just set the grid to the new dataSource.
This avoids the k-rebind behaviour...which I believe is documented: http://docs.telerik.com/kendo-ui/AngularJS/introduction#widget-update-upon-option-changes
This approach is not suitable for dataBound widgets because those widgets are recreated on each change of their data—for example, after paging of the Grid.
Note, I don't really know angular so there may be a better way to organize this code, but it works.

Assigning selected rows as other grid datasource

I am working on setting up a scenario as following:
1) User is shown existing results on first grid
2) User can select multiple results and click an 'Edit' button which will extract the selected items from the first grid
3)Second grid will be populated with the rows the user has selected from the first grid and will allow them to make edits to the content
4)Pressing save will update the results and show the first grid with the rows updated
So far using drips and drabs of various forum threads (here and here), I have managed to accomplish the first two steps.
$("#editButton").kendoButton({
click: function () {
// extract selected results from the grid and send along with transition
var gridResults = $("#resultGrid").data("kendoGrid"); // sourceGrid
var gridConfig = $("#resultConfigGrid").data("kendoGrid"); // destinationGrid
gridResults.select().each(function () {
var dataItem = gridResults.dataItem($(this));
gridConfig.dataSource.add(dataItem);
});
gridConfig.refresh();
transitionToConfigGrid();
}
});
dataItem returns what i am expecting to see with regards to the selected item(s) - attached dataItem.png. I can see the gridConfig populating but with blank rows (gridBlankRows.png).
gridConfig setup:
$(document).ready(function () {
// build the custom column schema based on the number of lots - this can vary
var columnSchema = [];
columnSchema.push({ title: 'Date Time'});
for(var i = 0; i < $("#maxNumLots").data("value"); ++i)
{
columnSchema.push({
title: 'Lot ' + i,
columns: [{
title: 'Count'
}, {
title: 'Mean'
}, {
title: 'SD'
}]
});
}
columnSchema.push({ title: 'Comment'});
columnSchema.push({ title: 'Review Comment' });
// build the datasource with CU operations
var configDataSource = new kendo.data.DataSource({
transport: {
create: function(options) {},
update: function(options) {}
}
});
$("#resultConfigGrid").kendoGrid({
columns: columnSchema,
editable: true
});
});
I have run out of useful reference material to identify what I am doing wrong / what could be outstanding here. Any help/guidance would be greatly appreciated.
Furthermore, I will also need functionality to 'Add New' results. If possible I would like to use the same grid (with a blank datasource) in order to accomplish this. The user can then add rows to the second grid and save with similar functionality to the update functionality. So if there is any way to factor this into the response, I would appreciate it.
The following example...
http://dojo.telerik.com/EkiVO
...is a modified version of...
http://docs.telerik.com/kendo-ui/framework/datasource/crud#examples
A couple of notes:
it matters if you are adding plain objects to the second Grid's dataSource (gridConfig.dataSource.add(dataItem).toJSON();), or Kendo UI Model objects (gridConfig.dataSource.add(dataItem);). In the first case, you will need to pass back the updated values from Grid2 to Grid1, otherwise this will occur automatically;
there is no need to refresh() the second Grid after adding, removing or changing its data items
both Grid dataSources must be configured for CRUD operations, you can follow the CRUD documentation
the Grid does not persist its selection across rebinds, so if you want to preserve the selection in the first Grid after some values have been changed, use the approach described at Persist Row Selection

How to prevent Row selection on custom elements click in UI-GRID

I'm facing a problem in using UI-GRId with row selection and custom cell elements:
The sample plunker is here : http://plnkr.co/edit/Ed6s6CGFGXyUzj2cyx2g?p=preview
$scope.gridOptions = { showGridFooter:true,enableRowSelection: true, enableRowHeaderSelection: false };
$scope.gridOptions.columnDefs = [
{ name: 'id' },
{ name: 'name'},
{ name: 'age', displayName: 'Age (not focusable)', allowCellFocus : false },
{ name: 'address.city' },
{ name:'address.pin',cellTemplate:'<select><option value="122002">122002</option><option value="122001">122001</option></select>'}];
You can see that on row click, the respective row gets selected, while if you tend to select the dropdown options implicitly the row selection event also gets fired, I want that on elements click like dropdown here the row selection event should not be triggered.
Pls guide.
Interesting question, haven't run into it yet, but I am sure it's only time before I do. I've created a plunk to demonstrate my solution.
Basically, what I have do is registered a watcher, as mentioned by AranS. From there, we have two objects to work with: the row, and the event that occured. Since the event object discloses which element was selected (clicked), we can identify if it was a DIV, or something else. In the event of the change in the select list, the value of evt.srcElement.tagName is 'SELECT'.
http://plnkr.co/edit/k2XhHr2QaD1sA5y2hcFd?p=preview
$scope.gridOptions.onRegisterApi = function( gridApi ) {
$scope.gridApi = gridApi;
gridApi.selection.on.rowSelectionChanged($scope,function(row,evt){
if (evt)
row.isSelected = (evt.srcElement.tagName === 'DIV');
});
};
ui-grid's API allows controlling row selection. Look at this answer from another thread: https://stackoverflow.com/a/33788459/5954939. Basically you can use the event rowSelectionChanged or the isRowSelectable. Let me know if you need an example.

Select2 4.0.0 multi-value select boxes - initial selection

I am attempting to have Select2 (4.0.0rc1) multi-value select box have preloaded data, but it is not working.
HTML
<select id="sj" class="js-example-basic-multiple form-control" multiple="multiple">
<option value="1">Tickets</option>
<option value="2">PArking</option>
<option value="3">Special Events</option>
<option value="4">Athletics</option>
</select>
JavaScript
$(document).ready(function() {
$("#sj").select2();
$("#example tbody").on("click", "tr",function(){
var defaultData = [{id:1, text:'Tickets'},{id:2,text:'Parking'},{id:3,text:'Athletics'}];
$("#sj").select2({data:defaultData});
});
I want this code to programmatically prepopulate the selected items on click.
EDIT
what I'm after: The drop down has a total of N Multi- selectable items , i click on a row , and it passes in 3 options as initially selected, how do i do an initSelection as 3.5.2 did? Think of it this way: I am using the multi select drop down to show attributes associated, if its a sporting event, It may only come with tickets, but a week from now i may want to add parking for this event, but it needs to remember I already had tickets associated with this event
I accomplished this in 3.5.2 doing the following:
initSelection : function (element, callback) {
var id=$(element).val();
if (id!=="") {
$.ajax("index.cfm/tickets/select2get", {
dataType: 'json',
data: {
nd_event_id: $('#nd_event_id').val(),
passes: 'TK,PK,ATH',
},
}).done(function(data) { callback(data); });
}
},
But this will not work in 4.0.0 due to migration from inputs to selects
Easier to understand if we separate the logic/code into smaller chunks and then tie them together... easier to debug as well if things go wrong. So you'll need:
Drop-down items to populate in the format of (key, value) which the
Select2 format is (id, text). You've got that correct, so let's
put that into a variable:
var infoCategory = [
{
"id": 1,
"text": "Tickets"
},
{
"id": 2,
"text": "Parking"
},
{
"id": 3,
"text": "Special Events"
},
{
"id": 4,
"text": "Athletics"
}
];
Select2 needs to know about the dropdown items we just created and it will be looking for a configuration of data as well as other options. Basically, "data" is one of the configuration options you pass along to it, if the <select> element doesn't have any <option> child elements. So let's create another variable for the Select2 configuration options as such:
var select2Options = {
"multiple" = false,
"data" = infoCategory
};
A full list of the default Select2 options can be found in their documentation.
Create the <select> element:
<select id="name="s2select01"></select>
Now, either you can directly initialize Select2 with configuration options (which includes drop-down data), like you did in your example, as such:
$('#s2select01').select2(select2Options);
Or you can use the above initialization line of script in a click event and tie it to another element, like so:
$('#someButtonID').click(function () {
$('#s2select01').select2(select2Options);
});
I've created a verbose demonstration on CodePen so you can see it all tied together.

Categories

Resources