My Angular autocomplete is using an object array and returning the correct result list. I can access the variables and map them to name and id field, but once I do this my drop down selector won't display text.
Here is the fiddle I started with and works correctly: http://fiddle.jshell.net/59nq55rf/
Here is the fiddle using the array and fails to display text in the drop down:
http://fiddle.jshell.net/ua1r8kjv/
$(function () {
var categoryList = [
{ "CategoryName": "Groceries", "CategoryID": "1" },
{ "CategoryName": "Games", "CategoryID": "2" },
{ "CategoryName": "Gadgets", "CategoryID": "3" },
]
$("#Category").autocomplete({
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
var matching = $.grep(categoryList, function (value) {
var name = value.CategoryName;
var id = value.CategoryID;
return matcher.test(name) || matcher.test(id);
});
response(matching);
}
});
});
HTML
<div class="ui-widget">
<form>
<label for="txtEmployeeName">Developer:</label>
<input id="Category" />
</form>
</div>
It definitively has to do with the jQuery UI library. It seems that it is expecting the property names to be exactly "value" and "id", anything else will not work. Run the code snippet below and test it with the letter 'g' to see for yourself. The result will correctly show 3 but fail to display the ones with the incorrect property names.
$(function () {
var categoryList = [
{ "value": "Groceries", "id": "1" },
{ "categoryname": "Games", "categoryid": "2" },
{ "doIwork": "Gadgets", "doIworkId": "3" },
]
$("#Category").autocomplete({
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
var matching = $.grep(categoryList, function (value) {
var name = value.categoryname || value.doIwork || value.value;
var id = value.categoryid || value.doIworkId || value.id;
return matcher.test(name) || matcher.test(id);
});
response(matching);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div class="ui-widget">
<form>
<label for="txtEmployeeName">Developer:</label>
<input id="Category" />
</form>
</div>
This is my custom solution for the answer posed above by #Urielzen
_CustomPair[] pairList = new _CustomPair[length];
private class _CustomPair
{
public string value;
public string id;
public _CustomPair(string curval, string curid)
{
value = curval;
id = curid;
}
}
Related
I have JSON data hundreds of entries like this:
{
"product":"Protec",
"type":"Central Opening",
"attribute":"Triple Lock",
"height":"2100",
"width":"1600",
"price":"3000"
},
{
"product":"Protec",
"type":"Sliding Door",
"attribute":"Single Lock",
"height":"2100",
"width":"1600",
"price":"3000"
},
{
"product":"ForceField",
"type":"Hinge Door",
"attribute":"Triple Lock",
"height":"2300",
"width":"1200",
"price":"100"
},
my vue component
var distinct_product = new Vue({
el: '#distinct',
data:{
distinct_product: [],
all_products: []
},
I fetch it and store it in my vue component and store it in a second data so when I render it to the ui the user only sees distinct elements.
mounted: async function(){
fetch("/Data/products.json")
.then(res => res.json())
.then(res => {
this.all_products = res
this.distinct_product = res
var disProduct = [...new Set(this.distinct_product.map(x => x.product))]
var disType = [...new Set(this.distinct_product.map(x => x.type))]
var disAttribute = [...new Set(this.distinct_product.map(x => x.attribute))]
this.distinct_product.productArray = disProduct;
this.distinct_product.typeArray = disType;
this.distinct_product.attributeArray = disAttribute;
My problem is, it also renders elements that aren't available to certain products.
for example a product : 'Window' can't have the attribute : 'triple locks'
I was wondering if I could filter/map the all_products array as the user selects a product.
I looked into computed properties mainly but I'm not sure of a good way to do it. this is my first attempt at a web app and I'm fairly new to JS too.
I aimed to iterate through the array pushing only objects containing the product selected in the UI
atm this is what I've attempted with no luck:
this.distinct_product.product which is bound to the UI
for (var i = 0; i < this.all_products.length; i++){
if (this.all_products[i] === this.distinct_product.product){
this.product.push(i);
return this.product;
}
}
so it would iterate over all_products looking for objects containing this.distinct_product.product which would contain 'Protec' or another product
Am I going at this the wrong way? should I step back in general and try and work with that data a different way?
Sorry if the question is structured poorly it's a skill I'm trying to work on, criticism is welcomed.
You are on the right track. I'll share a simple example so you can understand and make changes to your code accordingly.
var productdata = [
{
"product": "Protec",
"type": "Central Opening",
"attribute": "Triple Lock",
"height": "2100",
"width": "1600",
"price": "3000"
},
{
"product": "Protec",
"type": "Sliding Door",
"attribute": "Single Lock",
"height": "2100",
"width": "1600",
"price": "3000"
},
{
"product": "ForceField",
"type": "Hinge Door",
"attribute": "Triple Lock",
"height": "2300",
"width": "1200",
"price": "100"
},
];
//setTimeout(function () {
distinct_productVue = new Vue({
el: '#distinct',
data: {
//selected: {},
distinct_products: [],
all_products: productdata.map(function (x, index) {
return { text: x.product, value: index + 1 };
}),
selected: '0'
},
computed: {
},
mounted: function () {
this.all_products.unshift({ text: 'Please select a product', value: 0 });
},
methods: {
getDistinctProduct: function () {
var self = this;
self.distinct_products = productdata.filter(function (x, index) {
if (x.product === self.all_products[self.selected].text) {
return { text: x.product, value: index };
}
else { return false; }
});
}
}
});
<html>
<head>
<script src='https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.0/vue.min.js'></script>
</head>
<body>
<div id="distinct">
<select v-model="selected" v-on:change="getDistinctProduct">
<option v-for="option in all_products" v-bind:value="option.value">
{{ option.text }}
</option>
</select>
<!--<span>Selected: {{ selected }}</span>-->
<div v-show="selected != 0" style="margin-top:15px;">
<b>Available products</b>
<div v-for="pro in distinct_products" style="margin-top:15px;">
<div>product: {{pro.product}}</div>
<div>type: {{pro.type}}</div>
<div>attribute: {{pro.attribute}}</div>
<div>height: {{pro.height}}</div>
<div>width: {{pro.width}}</div>
<div>price: {{pro.price}}</div>
</div>
</div>
</div>
</body>
</html>
A quick question:
I'm creating a filter in angularjs to get dynamically a variable and to be used like this from frontend.
<div ng-if="(services | searchValue : 'type' : 'facebook').active == true">
...
</div>
This is the javascript.
.filter('searchValue', function () {
return function (array, name_var, value) {
angular.forEach(array, function(v, k) {
if (v[name_var] == value) {
return v;
}
});
return [];
};
})
Unfortunately even if the result was found it wasn't passed to the template.
If I'll use it like this:
{{(services | searchValue : 'type' : 'facebook')}}
This will get no value. Any suggestion?
I've created a sample example for the info you've provided. Run the below example check. Hope this helps you.
I guess ng-if itself expects only the variable and not the expression. only provide the variable with value i.e (services | searchValue : 'type' : 'facebook').active not the expression.
var app = angular.module('application', []);
app.filter('customfilter', function() {
return function(array, name_var, value) {
var filteredArray = {};
angular.forEach(array, function(v, k) {
if (v[name_var] == value) {
filteredArray = v;
return false;
}
});
return filteredArray;
}
});
app.controller('sampleController', function($scope, $filter) {
$scope.data = [{
"type": "facebook",
"active": false
}, {
"type": "linkedin",
"active": false
}, {
"type": "twitter",
"active": false
}, {
"type": "google",
"active": false
}];
$scope.anotherdata = [{
"type": "facebook",
"active": true
}, {
"type": "linkedin",
"active": false
}];
});
<script data-require="angular.js#1.3.x" src="https://code.angularjs.org/1.3.17/angular.js" data-semver="1.3.17"></script>
<body ng-app="application">
<div ng-controller="sampleController">
First div - Active : false
<div ng-if="(data | customfilter:'type':'facebook').active">
Your div content goes over here
</div>
<br>
<br>Second div - Active : true
<div ng-if="(anotherdata | customfilter:'type':'facebook').active">
Second div rendered
</div>
</div>
</body>
What am I doing wrong with my bindings? I simply get [object HTMLElement] returned for each one.
Please note this is a pared-down version and I will be wanting to access the full range of the JSON values.
Fiddle:
https://jsfiddle.net/0416f0s7/2/
Code:
<div data-bind="text: intro"></div>
function ViewModel(stories) {
var self = this;
self.stories = ko.observableArray(ko.utils.arrayMap(stories, function(story) {
return story.stories;
}));
};
$.getJSON('data.json', function(data) {
window.storyViewModel = new ViewModel(data.stories);
ko.applyBindings(window.storyViewModel);
});
JSON (filename data.json):
{
"stories": [
{
"intro": "Hi",
"outro": "Bye",
"elements": [
{
"title": "Title 1",
"image": "img/image1.jpg",
"paragraph": "Wordswordswords"
},
{
"title": "Title 2",
"image": "img/image2.jpg",
"paragraph": "More wordswordswords"
}
]
}
]
}
Your html change to
`<div data-bind="foreach:stories">
<div data-bind="text: intro"></div>
</div>
your code change to
function test(stories) {
var self = this;
self.stories = ko.observableArray(ko.utils.arrayMap(stories, function (story) {
return story;
}));
}
Good morning, i'm new to angularjs and want to practice it more, and here i have a question regarding a simple case while trying to learn to build my own angularjs webpage.
I have these two sets of data
$scope.data1 = [{ id: 1, name: "abc" },
{ id: 2, name: "efg" }]
$scope.data2 = [{ id: 1, info: "this is abc" },
{ id: 2, info: "absolutely not abc"}]
$scope.user = {
id: "",
name: "",
info: ""
}
and i have this input
<input ng-blur="passTheValue()" ng-model="user.idx" ng-type="text" placeholder="write name here"></input>
where i can write name on the text box.
my question is, how to pass all the value from data1 and data2 to $scope.user based on what input i have entered? For example, i write "abc" on the textbox, then my $scope.user will contain
id: 1, name: "abc", info: "this is abc"
i've tried to use $filter but i'm stuck at passing the value to the scope.
i'm sorry for my English, it's not my main language.
This is not the classical usecase for a filter: Do the processing of your data in the passTheValue() function.
this.passTheValue = function(){
$scope.data1.forEach(function(value, index, array){
if(value.name == $scope.idx){
$scope.user = {id: value.id, name: value.name, info: $scope.data2[index] }
}
})
}
HTML
<input ng-blur="passTheValue(user.idx)" ng-model="user.idx" ng-type="text" placeholder="write name here"></input>
Angular
$scope.passTheValue = function(name) {
angular.forEach($scope.data1, function(value, key){
if(value.name == name){
$scope.user.id = value.id;
$scope.user.name= value.name;
$scope.user.info = $scope.data2.filter(function(v) {
return v.id === value.id; // Filter out the appropriate one
})[0].info;
console.log($scope.user.id);
console.log($scope.user.name);
console.log($scope.user.info);
}
});
}
In your HTML , I've replaced the user.idx by name because you're searching by name. Sample on Plunker : https://plnkr.co/edit/bumDWC713dVWGnKoO5G3?p=preview
<body ng-app='app'>
<div ng-controller='appCtrl'>
<input ng-blur="passTheValue()" ng-model="name" ng-type="text" placeholder="write name here">
</div>
</body>
In your javascript, I add to simply search methods.
var app = angular.module('app',[])
.controller('appCtrl',function(){
$scope.data1 = [{
id: 1,
name: "abc"
},
{
id: 2,
name: "efg"
}];
$scope.data2 = [{
id: 1,
info: "this is abc"
},
{
id: 2,
info: "absolutely not abc"
}];
$scope.name = "";
$scope.user = {
id: "",
name: "",
info: ""
};
function findIdByName(name) {
for (var i = 0 ; i< $scope.data1 ; i++) {
if($scope.data1[i].name == name)
return $scope.data1[i].id;
}
return -111 ; //Assume that it's an impossible ID
}
function findInfoById(id) {
for (var i = 0 ; i< $scope.data2 ; i++) {
if($scope.data1[i].id == id)
return $scope.data1[i].info;
}
return -111 ; //Assume that it's an impossible Info
}
$scope.passTheValue = function(){
var id = findIdByName($scope.name);
if(id != -111){
var info = findInfoById(id);
if(info != -111){
$scope.user.id= id;
$scope.user.name = $scope.name;
$scope.info = info;
}else {
console.log(id,"Id doesn't exist in $scope.data2")
}
}else {
console.log(name,"name doesn't exist in $scope.data1")
}
}
});
I have a jQuery script that will get a JSON response and create as many "player" objects as there are in the response.
It will then add to availablePlayers which I then use as the variable for the source: field of autocomplete
When a user selects a player name and clicks the "add" button it will, at the moment, just display the guid and name of a player.
However, no matter what letters I type, all the players are given as an option. To illustrate this, if I type "Z" and none of the players have Z in their name, they options are still displayed.
How can I refine this functionality?
HTML
<div class="player-widget">
<label for "players">Players</label>
<input id="player" />
<input id="playerGUID" hidden />
<button id="add">Add</button>
</div>
jQuery
$(document).ready(function(){
var availablePlayers = []; // BLANK ARRAY OF PLAYERS
$("#player").autocomplete({
source: availablePlayers,
response: function (event, ui) {
ui.content = $.map(ui.content, function(value, key) {
return {
label: value.name,
value: value.guid
}
});
},
focus: function(event, ui) {
$("#player").val(ui.item.label);
return false;
},
select: function (event, ui) {
$("#player").val(ui.item.label); // display the selected text
$("#playerGUID").val(ui.item.value); // save selected id to hidden input
return false;
}
});
$.getJSON("http://localhost/Websites/Player-Widgets/service.php", function(data) {
var feedHTML = '';
// LOOP THROUGH EACH PLAYER
$.each(data.players, function(i, player) {
// DEFINE VARIABLES - BASED ON PLAYER ATTRIBUTES
var guid = player.guid;
var name = player.name;
var dob = player.date_of_birth;
var birth = player.birthplace;
var height = player.height;
var weight = player.weight;
var position = player.position;
var honours = player.honours;
// CREATE NEW PLAYER (OBJECT)
var player = {
guid: guid,
name: name,
position: position
};
// ADD TO PLAYER TAG ARRAY
availablePlayers.push(player);
});
console.log("User friendly array");
$.each(availablePlayers, function(i, val) {
console.log(val.guid + " - " + val.name + " [" + val.position + "]");
});
console.log("Array printout");
console.log(JSON.stringify(availablePlayers));
}).done(function(){
console.log("Done! Success!");
$("#player").autocomplete("option", "source", availablePlayers);
});
$("#add").click(function() {
alert($("#playerGUID").val() + " - " + $("#player").val());
});
});
Sample JSON response
{
"players": [
{
"guid": "1",
"name": "Matias Aguero",
"date_of_birth": "1981-02-13",
"birthplace": "San Nicolas, Argentina",
"height": "1.83m (6' 0\")",
"weight": "109kg (17st 2lb)",
"position": "Prop",
"honours": "40 caps"
},
{
"guid": "2",
"name": "George Catchpole",
"date_of_birth": "1994-02-22",
"birthplace": "Norwich, England",
"height": "1.85em (6ft 1\")",
"weight": "104kg (16st 5lb)",
"position": "Centre",
"honours": ""
}
]
}
Your problem is in the source function.
Source function uses request to pass term param to query, and you are ignoring it.
If you're using availablePlayers to query, you should use
source: availablePlayers
and your current function to map {label, text} object in response parameter.
response: function (event, ui) {
ui.content = $.map(ui.content, function(value, key) {
return {
label: value.name,
value: value.guid
}
});
}