Preselect options in select2 from json - javascript

As with disabled: true and locked: true is there a way to preselect an option in select2?
I have a text field that gets json data and i want to preselect an option
Is there something like this?
{id: 0, text: 'story'},{id: 1, text: 'bug', selected: true},{id: 2, text: 'task'}
I know it can be done with initSelection but i don't understand how to get selected: true
Can you help please?
Look at the code here:
http://jsfiddle.net/9PZTm/1/

I found something that worked for me
Here is the code if someone need it:
var items = [{id: 0, text: 'story'},{id: 1, text: 'bug', selected: true},{id: 2, text: 'task'}];
$(".form-control").select2({
createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term, selected:term};} },
multiple: false,
data: items,
width: 218,
initSelection : function (element, callback) {
$(items).each(function(){
if (this.selected != undefined){
callback(this);
}
});
},
});
http://jsfiddle.net/9PZTm/2/

I used an array instead
let arr = ['1','0'];
$('#multiple').val(arr).select2();

Related

How can you get Tabulator to use Select2 header filter?

Following the example here, we've been trying for over a week to get Tabulator working with a Select2 header filter. There is a JS Fiddle here with all the pieces. It seems like the Tabulator filter (which are really just editors) onRendered() function is not even getting called because the console log we have inside it never gets logged.
The select element itself shows up in the header filter, but never gets the Select2 object applied (probably because the onRendered seems to not even be called). If we put the Select2 object outside the onRendered function, it get applied, but then the filter does not get applied after selection is made. There are no console or other errors and we've followed the Tabulator 'example' to the letter, so we are not sure what to try next.
Does anyone know how to get a basic Select2 header filter functioning with Tabulator?
var tableData = [{
id: "1",
topic: "1.1"
},
{
id: "2",
topic: "2.2"
},
];
var select2Editor = function(cell, onRendered, success, cancel, editorParams) {
var editor = document.createElement("select");
var selData = [{
id: '1.1',
text: "One"
}, {
id: "2.2",
text: "Two"
}, {
id: "3.3",
text: "Three"
}, ];
onRendered(function() {
// TODO: map tracks to id and text
console.log('rendered');
$(editor).select2({
data: selData,
minimumResultsForSearch: Infinity,
width: '100%',
minimumInputLength: 0,
//allowClear: true,
});
$(editor).on('change', function(e) {
success($(editor).val());
});
$(editor).on('blur', function(e) {
cancel();
});
});
return editor
};
var columns = [{
title: "ID",
field: "id"
}, {
title: "Topic",
field: "topic",
headerFilter: select2Editor,
}, ];
var table = new Tabulator("#table", {
placeholder: "No Data Found.",
layout: "fitData",
data: tableData,
columns: columns,
});
I'm new to both Tabulator and select2 and I think this is possibly a bad way to do it but it seems like it miiight work.
If you want to use select2 with text input elements, it looks like you need to use the full package.
https://jsfiddle.net/dku41pjy/
var tableData = [{
id: "1",
topic: "1.1"
},
{
id: "2",
topic: "2.2"
},
];
var columns = [{
title: "ID",
field: "id"
}, {
title: "Topic",
field: "topic",
headerFilter: 'select2Editor'
}, ];
var awaiting_render = [];
function do_render({ editor, cell, success, cancel, editorParams }) {
console.log('possibly dodgy onrender');
var selData = [{
id: '',
text: "-- All Topics --"
}, {
id: '1.1',
text: "One"
}, {
id: "2.2",
text: "Two"
}, {
id: "3.3",
text: "Three"
}, ];
$(editor).select2({
data: selData,
//allowClear: true,
});
$(editor).on('change', function(e) {
console.log('chaaaange')
success($(editor).val());
});
$(editor).on('blur', function(e) {
cancel();
});
}
function render_awaiting() {
var to_render = awaiting_render.shift();
do_render(to_render);
if(awaiting_render.length > 0)
render_awaiting();
}
Tabulator.prototype.extendModule("edit", "editors", {
select2Editor:function(cell, onRendered, success, cancel, editorParams) {
console.log(cell);
var editor = document.createElement("input");
editor.type = 'text';
awaiting_render.push({ editor, cell, success, cancel, editorParams });
return editor
},
});
var table = new Tabulator("#table", {
placeholder: "No Data Found.",
layout: "fitData",
data: tableData,
columns: columns,
tableBuilt:function(){
render_awaiting();
},
});
Edit: my suspicion is that onRendered only gets fired when these edit elements are used in cells to sope with the transition between showing just data and showing an editable field.

Select2 minimumInputLength Not Working After append()

In my select2, I use minimumInputLength option to start filtering after a certain length.
selectExample.select2({
minimumInputLength: 2
});
But after dynamically append new option with append() function, this minimumInputLength option is not working.
selectExample.append('<option value="10">Ten</option>');
What happened exactly? Is there a specific way to append new option for select2?
The current solution I use is redeclaring the .select2() with the minimumInputLength option included.
var dynamicOptions=[{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
$("#select2").select2('data', dynamicOptions);
this is how you need to add options

jqGrid not populating

I'm am new to jqGrid. I am trying to implement a jqGrid that is populated with data returned by a REST call and several checkboxes that a user can edit to upload a new object to the DB using another rest call. I am having trouble populating the grid.
The issue I am experiencing is that the grid seems to take up the vertical space on the page, but is not displaying any information. The headers of the grid displayed fine when I just had a grid with no data.
During debug with Chrome, I found that the properties I expected to be returned from the row object when evaluated in the console are not there, ie. they are undefined.
Here is the code I am using:
var RGrid = [];
$.ajax({
url: restApi + EndPoint + '/' + Number,
type: 'GET',
success: function (response) {
Object2 = response;
var rData = $('#ResGrid').jqGrid().getRowData();
for (var i = 0; i < Object2.Requests.length; i++) {
var existingRows = rData.filter(function (a) {
return a.rId == Object2.Requests[i].Resource.Id;
});
if (existingRows.length == 0) {
var newObj = {
a: Object2.Requests[i].Resource.Name,
e: Object2.Requests[i].Resource.Id,
f: Object2.Requests[i].Id,
d: false,
b: false,
c: false
};
RGrid.push(newObj);
$('#ResGrid').jqGrid('addRowData', 1, newObj);
}
}
},
error: function (textStatus) {
Error('We were unable to retrieve the item');
}
});
$('#ResGrid').jqGrid({
defaults: {
emptyrecords: "No items assigned",
loadtext: "Loading..."
},
data: RGrid,
autowidth: true,
datatype: "local",
colModel: [
{ label: 'a', name: 'a', align: 'left', editable: false },
{
label: 'b', name: 'b', align: 'center', editable: true, edittype: 'checkbox',
editoptions: { value: "True:False" },
formatter: "checkbox", formatoptions: { disabled: false }
},
{
label: 'c', name: 'c', align: 'center', editable: true, edittype: 'checkbox',
editoptions: { value: "True:False" },
formatter: "checkbox", formatoptions: { disabled: false }
},
{
label: 'd', name: 'd', align: 'center', editable: true, edittype: 'checkbox',
editoptions: { value: "True:False" },
formatter: "checkbox", formatoptions: { disabled: false }
},
{ name: 'e', hidden: true },
{ name: 'f', hidden: true }
],
rowNum: 1000,
height: 'auto',
viewrecords: true,
caption: "Desc",
grouping: false,
loadonce: true
});
I have tried not passing values for the checkbox columns and several overloads of the addRowData method, none have had an effect. Curiously, the objects passed to the RGrid array appear to have all the property-value pairs I expect, so I suspect the issue is either with the colModel declaration or the way I am using addRowData method.
EDIT: The json I receive from the server:
{"Id":4,"JobNumber":"PrNum75","OrderNumber":null,"QuoteNumber":"1401291641","QuoteId":33,"Requests":[{"Id":10,"PlannedDays":[{"Id":20,"Hours":4.0,"Date":"2014-02-20T00:00:00"}],"PlannedSkillDef":{"Id":1,"Description":"IPE Inspector","DefaultRate":200.0},"QuoteSection":{"Id":54,"Description":"Ves","NumberOf":5,"TotalServices":1000.0,"TotalConsumables":100.0,"TotalTravel":5.0,"TotalAmountPerVessel":1105.0,"TravelExpenses":[{"Id":26,"AgreedRate":3.0,"Quantity":1,"TravelDef":{"Id":1,"Description":"Resource & NDT Travel ","UnitDescription":"Km","DefaultRatePerUnit":3.0}},{"Id":27,"AgreedRate":2.0,"Quantity":1,"TravelDef":{"Id":2,"Description":"Mechanical Service Travel","UnitDescription":"Km","DefaultRatePerUnit":2.0}}],"Consumables":[{"Id":16,"Quantity":1,"AgreedPrice":100.0,"ConsumableDef":{"Id":3,"Description":"Cans of MT / PT consumables","UnitPrice":100.0}}],"Services":[{"Id":17,"ServiceDef":{"Id":1,"Description":"Non Destructive Testing - Inspections","DefaultSkill":{"Id":2,"Description":"CPV","DefaultRate":250.0},"TasksRequired":[{"Id":1,"Description":"Thickness Testing"},{"Id":2,"Description":"Surface Crack Testing"},{"Id":3,"Description":"Reporting"},{"Id":4,"Description":"NDT Travel"}],"TravelDefs":[{"Id":1,"Description":"Resource & NDT Travel ","UnitDescription":"Km","DefaultRatePerUnit":3.0},{"Id":2,"Description":"Mechanical Service Travel","UnitDescription":"Km","DefaultRatePerUnit":2.0}],"ConsumableDefs":[{"Id":3,"Description":"Cans of MT / PT consumables","UnitPrice":100.0}]},"DefaultSkill":{"Id":70,"Rate":0.0,"SkillDef":{"Id":2,"Description":"CPV","DefaultRate":250.0}},"AgreedSkill":{"Id":69,"Rate":250.0,"SkillDef":{"Id":1,"Description":"IPE Inspector","DefaultRate":200.0}},"ServiceTasks":[{"Id":92,"TaskHours":1,"NumberOfShifts":1,"NumberOfStaff":1,"ServiceTaskDef":{"Id":1,"Description":"Thickness Testing"}},{"Id":93,"TaskHours":1,"NumberOfShifts":1,"NumberOfStaff":1,"ServiceTaskDef":{"Id":2,"Description":"Surface Crack Testing"}},{"Id":94,"TaskHours":1,"NumberOfShifts":1,"NumberOfStaff":1,"ServiceTaskDef":{"Id":3,"Description":"Reporting"}},{"Id":95,"TaskHours":1,"NumberOfShifts":1,"NumberOfStaff":1,"ServiceTaskDef":{"Id":4,"Description":"NDT Travel"}}]}]},"Resource":{"Id":1,"ADUserName":"###","Name":"Matthew Smith","SkillDefs":[]},"ServiceDef":{"Id":1,"Description":"Non Destructive Testing - Inspections","DefaultSkill":{"Id":2,"Description":"CPV","DefaultRate":250.0},"TasksRequired":[{"Id":1,"Description":"Thickness Testing"},{"Id":2,"Description":"Surface Crack Testing"},{"Id":3,"Description":"Reporting"},{"Id":4,"Description":"NDT Travel"}],"TravelDefs":[{"Id":1,"Description":"Resource & NDT Travel ","UnitDescription":"Km","DefaultRatePerUnit":3.0},{"Id":2,"Description":"Mechanical Service Travel","UnitDescription":"Km","DefaultRatePerUnit":2.0}],"ConsumableDefs":[{"Id":3,"Description":"Cans of MT / PT consumables","UnitPrice":100.0}]}}],"Consumables":[],"TravelAllocations":[]}
The part of interest to me is WorkRequests, where I need the Name and the Id of the Resource.
you can try doing this in complete: function(){// here your jqgrid}:
"loadonce: true" no need to use this as your datatype is local
var RGrid = [];
$.ajax({
url: restApi + EndPoint + '/' + Number,
type: 'GET',
success: function (response) {
Object2 = response;
var rData = $('#ResGrid').jqGrid().getRowData();
for (var i = 0; i < Object2.Requests.length; i++) {
var existingRows = rData.filter(function (a) {
return a.rId == Object2.Requests[i].Resource.Id;
});
if (existingRows.length == 0) {
var newObj = {
a: jobObject2.Requests[i].Resource.Name,
b: jobObject2.Requests[i].Resource.Id,
c: jobObject2.Requests[i].Id,
d: false,
e: false,
f: false
};
RGrid.push(newObj);
}
}
},
error: function (textStatus) {
Error('We were unable to retrieve the item');
},
complete: function(){
$('#ResGrid').jqGrid({
defaults: {
emptyrecords: "No items assigned",
loadtext: "Loading..."
},
data: RGrid,
autowidth: true,
.........
}
});
It's better if you would use datatype: "json". In the case jqGrid will make the request to the server. You need just use url option like url: restApi + EndPoint + '/' + Number and jsonReader like jsonReader: {root: "Requests", repeatitems: false}. It will inform jqGrid where to find the data in the response. Additionally you would need to use jsonmap option to bind columns with the names 'a', 'b', 'c', ... to properties Resource.Name and other in the server response.
The mapping of jobObject2.Requests[i].Resource.Id and jobObject2.Requests[i].Id to 'b' and 'c' columns having formatter: "checkbox" seems me very suspected. It's strange to have ids which possible value could be True or False only. Additional problem is the usage of variable Object2 in the loop, but usage of undefined jobObject2 in the body of the loop. I suppose that minimal fixing of your current code would be: moving of creating of the grid inside of success or complete callback and replacing jobObject2 to Object2. I would see the problem as the next one. Your current question is: how to fill the grid with the data returned from the server.
The code which I suggest should look about the following:
$('#ResGrid').jqGrid({
datatype: "json",
url: restApi + EndPoint + '/' + Number,
gridview: true,
autoencode: true,
loadonce: true,
jsonReader: {
root: "Requests",
repeatitems: false
},
colModel: [
{ name: "a", jsonmap: "Resource.Name" },
{ name: "b", jsonmap: "Resource.Id", align: "center" },
{ name: "c", jsonmap: "Id", align: "center" }
]
...
});
UPDATED: The demo shows that posted above options work with the last version of JSON data which you posted.
I have figured out what the issue was. The code declaring and populating the jqGrid was in a script file, which in the page was referenced above the declaration of the table that was supposed to act as the grid. A basic novice mistake on my part.
Thank you all for trying to help me out, and sorry to take up your time. Guess it's back to C# for me...

Selecting rows from one grid & passing them to another grid

I'm trying to allow rows to be selected via checkboxes and for those selected rows and their IDs to be sent to another grid when a 'Submit' button is clicked. In other words, acting as some sort of filter.
I've contacted Telerik's support team and was advised to take the following steps in order to get it working:
Get the selected rows with the Select() method of the Grid
Loop through them & get the underlying item with the dataItem method
Save them into an array
Destroy the grid
Initialize a new grid by setting the data data
Here's a sample on JSBin that shows what I have in mind.
I'm not sure where to start honestly. I would really appreciate it if someone could point me in the right direction to any resources or guides that would be helpful. Thanks!
Assuming you are using RadGrid, make sure you have client side selection turned on, you would see something like this:
<ClientSettings>
<Selecting AllowRowSelect="True" />
<ClientEvents OnRowSelected="RowSelected" />
</ClientSettings>
On the input button, make sure to call your JS method as follows :
<input onclick="GetSelected();" .... >
Your JS code might look something like this :
function GetSelected() {
var grid = $find("<%=Your Grid's ClientID Here%>");
var MasterTable = grid.get_masterTableView();
var selectedRows = MasterTable.get_selectedItems(); // 1. Get the selected rows. The selected item can be accessed by calling the get_selectedItems() method of the GridTableView client-side object.
for (var i = 0; i < selectedRows.length; i++) {
var row = selectedRows[i];
// This is where you would have to insert it in a collection so that you can bind it to another grid... You will need to call .Rebind() once you assign the new datasource to the other grid.
}
Hopefully this will give you some idea.. I can see if I can find any examples on inserting rows into other grid if you get stuck.
check this code
html
<div id="grid1"></div>
<input type="button" value="Submit" onclick="Move()" />
<div id="grid2" ></div>
script
<script>
$(document).ready(function() {
var data1 = [
{ id: 1, rating: 3, year: 1997, title: "Rock" }
, { id: 2, rating: 5, year: 1999, title: "X-Man" }
, { id: 3, rating: 4, year: 2011, title: "World War Z" }
];
var grid1=$("#grid1").kendoGrid({
sortable: true
, silectable: true
, selectable: "multiple row"
, filterable: true
, pageable: true
, columns: [
{ template: "<input type='checkbox' class='checkbox' />", width: "40px" }
,{ field: "id", title: "Id", filterable: false }
, { field: "rating", title: "Rating", filterable: false }
, { field: "year", title: "Year", filterable: true, type: "string"}
, { field: "title", title: "Title" }
]
, dataSource: { page: 1,
pageSize: 5,
data: data1
}
}).data("kendoGrid");
grid1.table.on("click", ".checkbox", selectRow);
var data2 = [
{ id: 101, rating: 6, year: 2012, title: "The Impossible" }
, { id: 102, rating: 8, year: 2013, title: "Escape" }
, { id: 103, rating: 7, year: 2013, title: "Gravity" }
];
$("#grid2").kendoGrid({
sortable: true
, silectable: true
, selectable: "multiple row"
, filterable: true
, pageable: true
, columns: [
{ field: "id", title: "Id", filterable: false }
, { field: "rating", title: "Rating", filterable: false }
, { field: "year", title: "Year", filterable: true, type: "string"}
, { field: "title", title: "Title" }
]
, dataSource: { page: 1,
pageSize: 5,
data: data2
}
});
});
function Move() {
var grid1 = $("#grid1").data("kendoGrid");
var rows = grid1.select();
rows.each(function(index, row) {
var selectedRow = grid1.dataItem(row);
//-move to grid2
var grid2 = $("#grid2").data("kendoGrid");
var ins = { id: selectedRow.id, rating: selectedRow.rating, year: selectedRow.year, title: selectedRow.title }; //id=1,rating=9.2,year=1995,title="The Godfather"
grid2.dataSource.insert(ins);
});
rows.each(function() {
grid1.removeRow($(this).closest('tr'));
});
}
function selectRow() {
var checked = this.checked,
row = $(this).closest("tr");
if (checked) {
//-select the row
row.addClass("k-state-selected");
} else {
//-remove selection
row.removeClass("k-state-selected");
}
}
</script>
this will help you :)

Access additional fields at kendoDropDownList change event?

I need additional information associated to the selected item. how do I access to the additional fields at change event
var language = [
{value: "English", culture: "en-US", direction: "ltr", text: "English"},
{value: "עברית", culture: "he-IL", direction: "rtl", text: "עברית - Hebrew"},
{value: "Français", culture: "fr-FR", direction: "ltr", text: "Français - French"}
];
$('#input').kendoDropDownList({
'dataTextField': 'text',
'dataValueField': 'value',
'dataSource': language,
'index': 0,
'change': function (e) {
// how do I access here to 'culture' and 'direction' fields
}
});
You can use the dataItem method of the widget to retrieve the data for the selected item:
'change': function (e) {
var item = this.dataItem();
// item.culture and item.direction
}

Categories

Resources