How to get id of the selected item of combobox in dojo - javascript

how to get the fId of the selected fname?
Here's my code..
var fS = new Memory({ //store for the combo
data: [
{fN:"", fId:""}
]
});
var fCombo = new ComboBox({ //combo box
id: "fCombo",
name: "fCombo",
value: "Select",
searchAttr: "fName"
}, "fCombo");
fCombo.store = fStore;
dojo.xhrPost({
url: "XXX",
handleAs: "json",
load: function(response, ioArgs){
fCombo.store.data = response.xx;
return response;
},
error: function(response, ioArgs){
console.log("Error", response+' '+ioArgs);
return response;
}
});
dojo.connect(dijit.byId("fCombo"), 'onChange',function(e){
//code to write based on f id
}
I tried this..
var Id = fStore.getValue(dijit.byId("fCombo").data, "fName");
But couldn't.. It says object doesn't support this property
Please help..!

It's complaining because dijit.byId("farmCombo") returns the ComboBox, which doesn't support '.data'.
Instead of using 'connect', try using 'watch'. There are loads of things you can watch. 'value' will get you your pure value changes, but if you listen to 'item' changing, you'll get given the full old and new item, from which you can retrieve your item id.
e.g.
farmCombo.watch("item", function(what, oldVal, newVal) {
// selected farmid is newVal.farmId
});
Here's a sample which displays your selected id in a separate textbox:
http://jsfiddle.net/RoystonS/cH6hf/
If you don't specify which value to watch, your callback will show you all changes, which can be extremely useful.

Related

Select2 Trigger Additional Data

I'm trying to load additional data on my select (select2), but the Trigger Event is not loading the additional data. The code and results are shown below.
$('#section').select2();
var data = {
id: 1,
text: 'text_default',
anothertext: 'text_2'
};
var newOption = new Option(data.text, data.id, true, true);
$('#section').append(newOption).trigger('change'); //until this point, everything works
$('#section').trigger({
type: 'select2:select',
params: {
data: data
}
});
console.log($('#section').select2('data')[0]['text']);// return text_default
console.log($('#section').select2('data')[0]['anothertext']);// return undefined
console.log($('#section').select2('data')['anothertext']);//only for test, return undefined
console.log($('#section').data('anothertext'));//only for test, return undefined
Is anything wrong with the code?

ExtJs 4.1.2 ComboBox Update or Reload Based on another ComboBox

I'd like to know a way of how to update the list values of a ExtJs ComboBox. For instance, I have two comboboxs.
One Combobox determine what values the another ComboBox should have. So, after selecting some of those,
I click the drowndown list (combobox) to see the values. But i dont get reflected.
change: function (combofirst, record) {
Ext.Ajax.request({
-- -- --
-- -- --
success: function (response) {
var combosecond = Ext.getCmp('defaultPackageType');
//I am unable to update the combosecond from below snippet.
combosecond.store = Ext.create('Ext.data.Store', {
fields: ['value', 'display'],
data: [
["N", "No"],
["A", "All accounts"]
] //json response
});
},
failure: function (record, action) {}
});
});
In short, how can I change the values of a ComboBox already has with ajax only.
Hope someone can help me
Thanks
I would also agree to the comment, that creating every time a new store and bind it to the combobox is not the optimal solution. I don't know really the reason why this should be done, but nevertheless here is a working example by using bindStore:
https://fiddle.sencha.com/#view/editor&fiddle/3ci0
Ext.create('Ext.form.field.ComboBox', {
// ...
listeners: {
change: {
fn: function (cb) {
Ext.Ajax.request({
url: 'https://jsonplaceholder.typicode.com/albums',
method: 'GET',
timeout: 60000,
success: function (response) {
var jsonResp = response.responseText;
let jsonObj = Ext.JSON.decode(jsonResp, true)
var combo2 = Ext.getCmp('myCombo2');
combo2.bindStore(Ext.create('Ext.data.Store', {
fields: ['id', 'title'],
data: jsonObj
}));
}
});
}
}
}
});
For selection of value 1 the data is loaded from a different url.
But I would think about whether a new proxy call is necessary and whether you can achieve your requirements by using filters or something else.

$$Hashkey missing when trying to add object with push from autocomplete

Array with hardcoded object shows up in my ng-repeat.
$scope.deltagarelist = [{ label: "Nils", value: "3" }];
This is my javascript/angular hybrid code to get selected values from the autocomplete and push it into my objectarray.
$(".addDeltagare").autocomplete(
{
source: function (request, response) {
$.ajax({
url: url,
data: { query: request.term },
datatype: 'jsonp',
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Label,
value: item.Value
}
}));
}
});
},
minLength: 3,
select: function (event, ui) {
event.preventDefault();
addtolist(ui.item);
console.log($scope.deltagarelist);
$(this).val('');
},
focus: function (event, ui) {
$("#addDeltagare").val(ui.item.label);
return false;
}
});
And my function to push the object into my list.
function addtolist(item) {
$scope.deltagarelist.push({label:item.label,value:item.value});
}
My problem is that my hardcoded guy "Nils" gets a $$hashkey but when I add an object to the list in this way it doesnt get a hashkey and it adds to the array but doesnt show up in my repeat.
Any ideas on how I can change this code to make it work?
Or should I look for other autcompletes thats more "the angular way" ?
The solution is adding a track by to your ng-repeat so that AngularJS doesn't need to use the $$hashkey to track changes.
<div ng-repeat="val in deltagarelist track by val.value">
The $ajax is asynchronous, this means the NG-app is already been build before the data is downloaded. A workaround is to make $ajax sync sothat everything waits until the data is downloaded.

Refreshing gridx with server-side data

I'm thinking that I am overlooking something simple - I am so close to making this work. :)
I have a grid that needs to be updated with server information.
Here is the way that it should work:
A user selects an item
Make a JsonRest query with the item ID selected
Update the grid - showing notes relating to item selected
Here is how the grid is setup:
function noteTabSetup() {
var store = JsonRest({target:"//localhost/program/notes", idAttribute:"id"});
var structure = [{ field: 'id', name: 'Id', width: '5em' },
{ field: 'name', name: 'Name', width: '12%' },
{ field: 'description', name: 'Description' }];
var noteGrid = new Grid({
id: 'noteGrid',
pageSize: 20,
store: store,
cacheClass: Cache,
structure: structure,
filterServerMode: true,
selectRowTriggerOnCell: true,
bodyLoadingInfo: "Loading notes ...",
bodyEmptyInfo: "No notes found",
modules: [SingleSort, VirtualVScroller, moveColumn,
selectColumn, dndColumn, selectRow, Filter]}, noteTab);
noteGrid.startup();
When an item is selected, the selected item ID is passed to:
function noteLoad(itemId) {
console.log("In NoteLoad");
var grid = registry.byId("noteGrid");
if (!itemIds || 0 === itemIds.length) { console.log("no ItemId chosen"); }
else {
console.log("In NoteLoad with an itemId");
grid.model.clearCache();
// Error on second run
grid.store.query({ find: "ByItem", item: itemId }).then(function(result) {
grid.setStore(new ItemFileReadStore({data: {items : result}}));
});
grid.body.refresh();
console.log("model: " + grid.rowCount());
};
};
On the first item selected, everything works well - the query fires, and the grid is updated with notes related to the selected item.
On the second item selected, I receive this error from firebug:
TypeError: grid.store.query is not a function
grid.store.query({ find: "ByItem", item: itemIds }).then(function(result) {
-----------------------------------^
Any ideas?! Thank you in advance.
Chris
Thank you for the reply - that makes sense that store was being replaced by ItemFileReadStore. If possible, I would like to use JsonRest directly to update the grid.
I've tried a handful of variations based off of your comment, without luck:
Query fires and result is returned. Grid is not updated:
grid.model.clearCache();
grid.store.query({ find: "ByItem", item: itemIds }).then(function(results){
console.log('notes: ' + results[0].name);
});
grid.body.refresh();
Error: grid.store.fetch is not a function:
grid.store.fetch({ query: { find: "ByItem", item: itemIds }});
Syntax error in Dojo.js (line 15):
grid.store.query({ find: "ByItem", item: itemIds }).then(function(result) {
grid.setStore(new JsonRest({data: {items : result}}));
});
I've done a lot of searches and can't find a good example where the grid is being updated from a JsonRest object. Thank you.
Because the code itself replaces the store the first time.
grid.store.query({ find: "ByItem", item: itemId }).then(function(result) {
grid.setStore(new ItemFileReadStore({data: {items : result}}));
});
Here, the grid's store is initially JsonRest store, which after the query method is run, is replaced by the new ItemFileReadStore object. The mistake here is "query" is not a method of ItemFileReadStore, but the parameter passed to the "fetch" method. Check out some examples from dojo documentation on this.
On the other hand, JsonRest store has the method "query". Hence the contradiction. Change your code accordingly if you want ItemFileReadStore.
eg:-
store.fetch( { query: { name: 'Ice cream' },
onItem: function(item) {
console.log( store.getValue( item, 'name' ) );
console.log( 'cost: ', store.getValue( item, 'cost' ) );
}
});

twitter bootstrap typeahead (method 'toLowerCase' of undefined)

I am trying to use twitter bootstrap to get the manufacturers from my DB.
Because twitter bootstrap typeahead does not support ajax calls I am using this fork:
https://gist.github.com/1866577
In that page there is this comment that mentions how to do exactly what I want to do. The problem is when I run my code I keep on getting:
Uncaught TypeError: Cannot call method 'toLowerCase' of undefined
I googled around and came tried changing my jquery file to both using the minified and non minified as well as the one hosted on google code and I kept getting the same error.
My code currently is as follows:
$('#manufacturer').typeahead({
source: function(typeahead, query){
$.ajax({
url: window.location.origin+"/bows/get_manufacturers.json",
type: "POST",
data: "",
dataType: "JSON",
async: false,
success: function(results){
var manufacturers = new Array;
$.map(results.data.manufacturers, function(data, item){
var group;
group = {
manufacturer_id: data.Manufacturer.id,
manufacturer: data.Manufacturer.manufacturer
};
manufacturers.push(group);
});
typeahead.process(manufacturers);
}
});
},
property: 'name',
items:11,
onselect: function (obj) {
}
});
on the url field I added the
window.location.origin
to avoid any problems as already discussed on another question
Also before I was using $.each() and then decided to use $.map() as recomended Tomislav Markovski in a similar question
Anyone has any idea why I keep getting this problem?!
Thank you
Typeahead expect a list of string as source
$('#manufacturer').typeahead({
source : ["item 1", "item 2", "item 3", "item 4"]
})
In your case you want to use it with a list of objects. This way you'll have to make some changes to make it works
This should works :
$('#manufacturer').typeahead({
source: function(typeahead, query){
$.ajax({
url: window.location.origin+"/bows/get_manufacturers.json",
type: "POST",
data: "",
dataType: "JSON",
async: false,
success: function(results){
var manufacturers = new Array;
$.map(results.data.manufacturers, function(data){
var group;
group = {
manufacturer_id: data.Manufacturer.id,
manufacturer: data.Manufacturer.manufacturer,
toString: function () {
return JSON.stringify(this);
},
toLowerCase: function () {
return this.manufacturer.toLowerCase();
},
indexOf: function (string) {
return String.prototype.indexOf.apply(this.manufacturer, arguments);
},
replace: function (string) {
return String.prototype.replace.apply(this.manufacturer, arguments);
}
};
manufacturers.push(group);
});
typeahead.process(manufacturers);
}
});
},
property: 'manufacturer',
items:11,
onselect: function (obj) {
var obj = JSON.parse(obj);
// You still can use the manufacturer_id here
console.log(obj.manufacturer_id);
return obj.manufacturer;
}
});
In my case, I was getting this exact error, and it turned out that the version of Bootstrap I was using (2.0.4) did not support passing in a function to the source setting.
Upgrading to Bootstrap 2.1.1 fixed the problem.
UPDATED / REVISED LOOK AT THE ISSUE: The error you mentioned "Cannot call method 'toLowerCase' of undefined" occurred to me when I used the original Typeahead extension in bootstrap that does not support AJAX. (as you have found) Are you sure that the original typeahead extension isn't loading, instead of your revised one?
I have been sucessfully using this Gist of typeahead that is a slight variation on the one you mention. Once I switched to that Gist and confirmed that the input data was good (testing that the input was a string array in an JS object, the issue went away.
Hope this helps
Original answer:
The reason the error occurs is because the value passed into the typeahead matcher function is undefined. That is just a side effect to the real issue which occurs somewhere between your input and that matcher function. I suspect the 'manufacturers' array has a problem. Test it first to verify you have a valid array.
// It appears your array constructor is missing ()
// try the following in your binding code:
var manufacturers = new Array();
Here is what I am using to bind the input to typeahead. I confirmed that it works with your modified typeahead fork.
My HTML:
<!-- Load bootstrap styles -->
<link href="bootstrap.css" rel="stylesheet" type="text/css" />
...
<input type="text" class="typeahead" name="Category" id="Category" maxlength="100" value="" />
...
<!-- and load jQuery and bootstrap with modified typeahead AJAX code -->
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="bootstrap-modified-typeahead.js" type="text/javascript"></script>
My binding JavaScript code:
// Matches the desired text input ID in the HTML
var $TypeaheadInput = $("#Category");
// Modify this path to your JSON source URL
// this source should return a JSON string array like the following:
// string[] result = {"test", "test2", "test3", "test4"}
var JsonProviderUrl = "../CategorySearch";
// Bind the input to the typeahead extension
$TypeaheadInput.typeahead({
source: function (typeahead, query) {
return $.post(JsonProviderUrl, { query: query }, function (data) {
return typeahead.process(data);
});
}
});
In my case I had null values in my source array causing this error.
Contrived example:
source : ["item 1", "item 2", null, "item 4"]
Your manufacturer objects don't have a "name" property, you should change
property: 'name',
to
property: 'manufacturer',
Have you tried using mapping variables like example below, you need to use this when you got more then one property in your object;
source: function (query, process) {
states = [];
map = {};
var data = [
{"stateCode": "CA", "stateName": "California"},
{"stateCode": "AZ", "stateName": "Arizona"},
{"stateCode": "NY", "stateName": "New York"},
{"stateCode": "NV", "stateName": "Nevada"},
{"stateCode": "OH", "stateName": "Ohio"}
];
$.each(data, function (i, state) {
map[state.stateName] = state;
states.push(state.stateName);
});
process(states);
}
I stumbled upon this issue a while ago. I advice you to recheck configuration where you are including typeahead libraries (via main.js, app.js or config.js).
Otherwise, you can overwrite the latest Bootstrap version to your application library.
Try this code:
String.prototype.hashCode = function(){
var hash = 0;
if (this.length == 0) return hash;
for (i = 0; i < this.length; i++) {
char = this.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
};
var map_manufacter, result_manufacters;
$('#manufacturer').typeahead({
source: function(typeahead, query){
$.ajax({
url: window.location.origin+"/bows/get_manufacturers.json",
type: "POST",
data: "",
dataType: "JSON",
async: false,
success: function(results){
result_manufacter = [], map_manufacters = {};
$.each(results.data.manufacturers, function(item, data){
map_manufacters[data.Manufacturer.manufacturer.hashCode()] = data;
result_manufacters.push(data.Manufacter.manufacter);
});
typeahead.process(result_manufacters);
}
});
},
property: 'name',
items:11,
onselect: function (obj) {
var hc = obj.hashCode();
console.log(map_manufacter[hc]);
}
});
I solved this problem only updating the file bootstrap3-typeahead.min.js to the file in https://github.com/bassjobsen/Bootstrap-3-Typeahead/blob/master/bootstrap3-typeahead.min.js
I think most people can solve this way.

Categories

Resources