How to get an attribute from selected data item in Webix combo? - javascript

I have the following Webix combo:
{
view: "combo",
label: 'Select the name',
labelWidth:130,
options: {
data:[
{ itemId:"120", itemName:"Name 1"},
{ itemId:"121", itemName:"Name 2"}
],
body: { template: '#itemName#' }
},
on:{
onChange:function(id){ alert(id) }
}
}
It looks just as needed, but how can I get itemId after selecting new item? I can only get the auto-generated ID
The same code in a snippet:
http://webix.com/snippet/3a431f1c
Thanks in advance!

You have to get the object of the combobox and then you can get data of the selected item with the help of its getItem() method as:
var obj = this.getPopup().getBody().getItem(newValue); //the object
var id = obj.itemId; //the desired id which is itemId in your code
Please check the snippet here.

Related

KendoUI Grid: Add fields to Datasource dynamically

I have a Kendo DataSource that I'm binding to a grid. I'm adding a field dyanmically. This all works fine until I put a template on the column that I add dynamically.
Model Building:
model = kendo.data.Model.define({
id: "Id",
fields: {
}
});
model.fields["CreationDate"] = { type: "date" };
I then assign the model to the model property of the datasource. My grid is created like:
$("#Grid").kendoGrid({
dataSource: UserDS,
columns: [
{ "field": "CreationDate", template: '#= kendo.toString(CreationDate, "g") #' }
]
});
When I try to add a new record to this grid I get an error saying CreationDate is not define. If I remove the template part of the field definition it works. Also if I change the model to add the field as part of the model definition it works even with the template. I would expect the same end result from both approaches.
Try this:
var model ={
id: "Id",
fields: {}
};
model.fields["CreationDate"] = { type: "date" };
jsfiddle: http://jsfiddle.net/Sbb5Z/1599/

Get ID from selectize.js to form

I'm trying to set up a form on my site, and want to use some dynamic dropdown.
I found Selectize.js, which seems like a good solution, however I'm struggling to find out how to get the ID's from the selected option when I post the form.
As in user selects "Banana" and selectize should return 2 as value for the post
The obvious answer would of course be to change valueField to 'id' however that messes up the createFilter so that's a no go..
I've made a jsfiddle with what I have so far: http://jsfiddle.net/imfpa/Lh3anheq/16/
HTML:
<form>
<select id="item-type" placeholder="Choose type...">
</select>
</form>
javascript:
function hasOwnPropertyCaseInsensitive(obj, property) {
var props = [];
for (var i in obj) if (obj.hasOwnProperty(i)) props.push(i);
var prop;
while (prop = props.pop()) if (prop.toLowerCase() === property.toLowerCase()) return true;
return false;
}
var REGEX = '[a-zA-ZæøåÆØÅ][a-zA-ZæøåÆØÅ ]*[a-zA-ZæøåÆØÅ]';
$('#item-type').selectize({
persist: true,
valueField: 'text',
labelField: 'text',
searchField: ['text'],
options: [
{id: '1', text: 'Apple'},
{id: '2', text: 'Banana'},
{id: '3', text: 'Orange'},
{id: '4', text: 'Cherry'},
],
createFilter: function(input) {
var match, regex;
regex = new RegExp('^' + REGEX + '$', 'i');
match = input.match(regex);
if (match) {
console.log(match[0]);
return !hasOwnPropertyCaseInsensitive(this.options, match[0]);
}
return false;
},
create: true
});
jsFiddle demo (http://jsfiddle.net/json/Lh3anheq/35/)
Okay, based on our discussion in the comments above, you want the selectize.js to return the id of the selected item, and also let users create unique items.
You are right about the id: you just need to replace the valueField: 'text' with valueField: 'id'.
Now we need to fix the decision making in your function hasOwnPropertyCaseInsensitive.
The first argument in this function is an object of objects. If you see the console output, for this.options of your selectize element, you will see roughly the following structure (valueField is already replaced with id here):
{
idOfItem1: {
id: idOfItem1,
text: textOfItem1
},
idOfItem2: ...
}
Here is what the web inspector prints out for console.log(this.options):
So, we can iterate over all objects and still have the display value in the field text, and this is exactly the string that we need to compare against the user input for uniqueness.
function hasOwnPropertyCaseInsensitive(options, userValue) {
var exists = false;
for (var option in options) {
if (options.hasOwnProperty(option)) {
if (options[option].text.toLowerCase() === userValue.toLowerCase()) {
exists = true;
break; // break from the loop when the match is found. return true works as well.
}
}
}
return exists;
}
Note! The id of an element created by a user will be the same as the display value. I.e. if I add a new element to the list, e.g. Test, it will look like this:
{
Test: {
id: "Test",
text: "Test"
}
}
Please see the jsFiddle demo (http://jsfiddle.net/json/Lh3anheq/35/) and let me know if I missed something.

Dojotoolkit store.GetValue when TextBox inside

i have a question regarding the dojotoolkit.
I have a DataGrid and want to get a value inside of it. The tricky part is, that the value is a
TextBox.
My structure for the DataGrid looks like this:
grid = new dojox.grid.DataGrid({
store: store,
structure: [
{
name: "Quantity", field: "Quantity", width: "30px",
formatter: function(item)
{
var tb = new dijit.form.TextBox(
{
name: "quantity",
value: "1",
placeHolder: "quantity",
});
return tb;
}
},
{ name: "Value", field: "Value", width: "auto"}
]
}, "bGrid");
I have furthermore a button which can be clicked.
If the button was clicked, this function is executed:
myClass.prototype.Test = function Test(tItem)
{
var item = tItem;
var val = grid.getItem(item.value); //Value in this case is an integer refering to the position of my item in the grid
var quantity;
var name;
if(val!==null){
var store = grid.store;
quantity = store.getValue(val, 'Quantity');
name = store.getValue(val, 'Value');
}
console.log("Quantity "+quantity+ " Name: "+name);
}
the name variable is set correctly but i don't get anything from quantity.
I would guess that i would get the TextBox but i receive nothing.
Does anybody know how to access the field of the store ?
I think because the Textbox is a widget you can get access to its value by setting an id for it and get the element by
dijit.byId("YourTB").get('value');
Regards, Miriam

Ext JS 4: Grid List Filter is NOT updated

I am running a weird problem when I try to set Grid Filter list dynamically.
Let me explain by my code snippets
I have a column with filter list is defined as
{
text : 'Client',
dataIndex : 'topAccount',
itemId : 'exTopAccount',
filter: {
type: 'list',
options:[]
}
}
I initialize list from store in 'viewready'
viewready: function(cmp,eOpts){
cmp.getHeaderCt().child('#exTopAccount').initialConfig.filter.options = clientsStore.collect('topAccount');
}
===> WORKS GOOD
Now, I have to build the new client store based on the records when user moves to next page. Therefore I build the store in the 'change' event of paging
listeners: {
'change' :function( toolbar, pageData, eOpts ) {
var store = Ext.StoreManager.get('ExceptionRecords');
clientsStore.removeAll(true);
store.each(function(record){
if(clientsStore.findRecord('topAccount',record.data.topAccount.trim()) == null ) {
clientsStore.add({topAccount: record.data.topAccount.trim()})
}
})
Ext.getCmp('exceptionGridContainer').view.refresh;
Ext.getCmp('exceptionGridContainer').view.getHeaderCt().doLayout;
console.log(clientsStore);
Ext.getCmp('exceptionGridContainer').view.getHeaderCt().child('#exTopAccount').initialConfig.filter.options = clientsStore.collect('topAccount');
}
}
I can now see the new data in clientsStore . But Grid filter list is not updated. still showing old data. I tried refresh,layout etc. Nothing helps
Any help will be appreciated
Thanks
Tharahan
Just changing the value of a property does not affect the component rendered or computed state. The menu is created when the list is first initialized. The first time you do that, it works because that's before the initialization, but the second time, that's too late.
If you can grab a reference to the instantiated ListFilter, I think you could force the recreation of the menu this way:
listFilter.menu = listFilter.createMenu({
options: [ ... ] // new options
// rest of the filter config
});
So, supposing you have a reference to your target grid, you could change the options for the column with dataIndex of "topAccount" by a call similar to this:
var listFilter = grid
.findFeature('filters') // access filters feature of the grid
.get('topAccount'); // access the filter for column
listFilter.menu = listFilter.createMenu({
options: [ ... ] // new options
// rest of the filter config
});
--- Edit ---
OK, complete example. Tested, working.
Ext.widget('grid', {
renderTo: Ext.getBody()
,height: 400
,features: [{
ftype: 'filters'
,local: true
}]
,columns: [{
dataIndex: 'a'
,text: 'Column A'
,filter: {
type: 'list'
,options: ['Foo', 'Bar']
}
},{
dataIndex: 'b'
,text: 'Column B'
},{
dataIndex: 'c'
,text: 'Column C'
}]
,store: {
fields: ['a', 'b', 'c']
,autoLoad: true
,proxy: {
type: 'memory'
,reader: 'array'
,data: [
['Foo', 1, 'Bar']
,['Bar', 2, 'Baz']
,['Baz', 1, 'Bar']
,['Bat', 2, 'Baz']
]
}
}
,tbar: [{
text: 'Change list options'
,handler: function() {
var grid = this.up('grid'),
// forget about getFeature, I read the doc and found something!
filterFeature = grid.filters,
colAFilter = filterFeature.getFilter('a');
// If the filter has never been used, it won't be available
if (!colAFilter) {
// someone commented that this is the way to initialize filter
filterFeature.view.headerCt.getMenu();
colAFilter = filterFeature.getFilter('a');
}
// ok, we've got the ref, now let's try to recreate the menu
colAFilter.menu = colAFilter.createMenu({
options: ['Baz', 'Bat']
});
}
}]
});
I was solving similar problem and answers to this question helped me a lot. Local List filter menu is in fact lazy loaded (only created when clicked) and I needed to set filter menu to be reloaded if the grid store has been reloaded with different data. Solved it by destroying of menu after each reload, so on next click menu is recreated:
var on_load = function() {
var grid_header = me.gridPanel.filters.view.headerCt
if (grid_header.menu) {
grid_header.menu.destroy();
grid_header.menu = null;
}
}

Data is not getting displayed in dojox.data.Datagrid on click event.

I want to display data in a data grid. The data is retrieved by a URL using $.get Method as a JSon type. I am not getting any error. But not getting Data grid as well. Here's me script code ::
<script type="text/javascript">
$("document").ready(function(){
$('#contentpaneid').bind('click', getInfoFromServer);
function getInfoFromServer(){
$.get("http://localhost:8080/2_8_2012/jsp/GetJson.jsp?random=" + new Date().getTime(), function (result) {
success:postToPage(result),
alert('Load was performed.');
},"Json");
function postToPage(data){
alert(data);
var storedata = {
identifier:"ID",
items: data //[{"ID":1,"Names":"Shantanu","Email":"shantanu.tomar#gmail.com"},{"ID":2,"Names":"Mayur","Email":"mayur.sharma#gmail.com"},{"ID":3,"Names":"Rohit"},{"ID":21,"Names":"Rakesh","Email":"askjhjk"}]
};
var store1 = new dojo.data.ItemFileWriteStore({data: storedata}) ;
var gridStructure =[[
{ field: "ID",
name: "ID_Emp",
width: "20%",
classes:"firstName"
},
{
field: "Names",
name: "Name",
width: "20%",
classes: "firstName"
},
{ field: "Email",
name: "Mail",
width: "20%",
classes:"firstName"
}
]
];
var grid = new dojox.grid.DataGrid({
store: store1,
structure: gridStructure,
rowSelector: '30px',
selectionMode: "single",
autoHeight:true,
columnReordering:true
},'gridDiv');
grid.startup();
dojo.connect(grid, "onSelectionChanged", grid, function(){
var items = grid.selection.getSelected();
// do something with the selected items
dojo.forEach(items, function(item){
var v = grid.store.getValue(item, "Names");
function showDialog() {
dojo.require('dijit.Tooltip');
dijit.byId("terms").show();
}
showDialog();
}, grid);
});
dojo.connect(grid, "onCellClick", grid, function sendmail(){
var items = grid.selection.getSelected();
dojo.forEach(items, function(item){
var v1 = grid.store.getValue(item, "Email");
alert(v1);
request.setAttribute("variablemail", v1);
});
});
};
};
});
</script>
My markup code is ::
<div id="contentpaneid" dojoType="dijit.layout.ContentPane" title="Pending Activities" style="background-image: url('http://localhost:8080/2_8_2012/images/17.png');">
<div data-dojo-id="gridDiv" title="Simple Grid" style="width:900px; height:200px;">
When i click inside content pane I get my alert(data) output as when retrieving data as JSon through $.get method ::
[Object object][Object object][Object object](The number of [Object object] depends on number of entries in Database)
And output when Retrieving data as Text is ::
[{"ID":1,"Names":"Shantanu","Email":"shantanu.tomar#gmail.com"},{"ID":2,"Names":"Mayur","Email":"mayur.sharma#gmail.com"},{"ID":3,"Names":"Rohit"},{"ID":21,"Names":"Rakesh","Email":"askjhjk"},{"ID":22,"Names":"Hello"}]
Now when i update the data I do get my data alert ryt. i.e value is getting updated in alert(data) my $.get function is working fine. And also getting alert('Load was performed.') message. But grid is not getting displayed. Its not the data .but grid is also not getting displayed. On click only alert boxes appear. that's it. Where am i making mistake ? And i should retrieved the data as text or JSON so that values are correctly passed on to "items:". please help. i want that on click event the grid refreshes itself according to changes in database. Thanks.
Change
<div data-dojo-id="gridDiv"...
to
<div id="gridDiv" ...
Note that data-dojo-id is meant to be used to create a global JS variable that holds the widget.
In your situation, you are populating the datagrid and asking dojo to replace a DOM node with id gridDiv with the datagrid. Since dojo is not able to find such a node, you are not seeing the datagrid

Categories