How to find the Exact word using Select 2 js? - javascript

I have integrated select2.js in my project cakephp
Js file code :
$(document).ready(function()
{
$('#RecipeIngredientId').select2().change();
$('#RecipeIngredientId').on('change', function()
{
var ingred_val = $(this).val();
$('#RecipeIngredientId').select2({
ajax: {
url: "<?php echo $this->webroot; ?>adminarea/recipe/ingredshow"+ '/' + ingred_val ,
dataType: 'json',
type: "GET",
data: function (term) {
return {
term: term
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.title,
id: item.id
}
})
};
}
}
})
})
});
We have already integrated the select 2 box js in the drop down, But we are not getting proper output
Output we are getting
while searching carrot from the dropdown ->
[0]=> baby carrot 1=> baby orange carrot [2]=> baby purple carrot
[3]=> carrot
I want to show like that : Carrot will be the first one
[0]=> carrot 1=> carrot clean [2]=> baby carrot
[3]=> baby purple carrot
( carrot ) text priorities first
Plugin we have already used :
sorter
matcher
processResult
Updated file
$(document).ready(function(){
$('#RecipeIngredientId').on('change', function()
{
var ingred_val = $(this).val();
$('#RecipeIngredientId').select2({
processResults: function (data) {
var order = [];
$.each(data, function(k,v){
if(v.title.indexOf(ingred_val) in order){
order[v.title.indexOf(ingred_val)+1] = v.title;
} else {
order[v.title.indexOf(ingred_val)] = v.title;
}
});
data = order.clean(undefined); //remove undefined indexes from array
return {
results: $.map(data, function (item) {
return {
text: item.title,
id: item.id
}
})
};
}
})
});
Array.prototype.clean = function(deleteValue) {
for (var i = 0; i < this.length; i++) {
if (this[i] == deleteValue) {
this.splice(i, 1);
i--;
}
}
return this;
};
$('#RecipeIngredientId').select2().change();
});

You can use this script.
processResults: function (data) {
var order = [];
$.each(data, function(k,v){
if(v.indexOf("carrot") in order){
order[v.indexOf("carrot")+1] = v;
} else {
order[v.indexOf("carrot")] = v;
}
});
data = order.clean(undefined); //remove undefined indexes from array
return {
results: $.map(data, function (item) {
return {
text: item.title,
id: item.id
}
})
};
}
Array.prototype.clean = function(deleteValue) {
for (var i = 0; i < this.length; i++) {
if (this[i] == deleteValue) {
this.splice(i, 1);
i--;
}
}
return this;
};
So first you can check the occurrence index the word "carrot" in data value by looping through them. We are using indexOf for this purpose. After that you will get an sorted array with least occurrence index as lower key. Now we need to remove undefined values from the generated array. So for that I have used a function called "clean" (Don't forget to add this function in your JS). And you will get the sorted Array.
Here is a Fiddle.
Update
Dynamic input value
processResults: function (data) {
var order = [];
$.each(data, function(k,v){
if(v.indexOf("carrot") in order){
order[v.indexOf("carrot")+1] = v;
} else {
order[v.indexOf("+ingred_val+")] = v;
}
});
data = order.clean(undefined); //remove undefined indexes from array
return {
results: $.map(data, function (item) {
return {
text: item.title,
id: item.id
}
})
};
}
Array.prototype.clean = function(deleteValue) {
for (var i = 0; i < this.length; i++) {
if (this[i] == deleteValue) {
this.splice(i, 1);
i--;
}
}
return this;
};
Just replace "carrot" with variable ingred_val where you have set the value of select box.
Update 2
processResults: function (data) {
var order = [];
$.each(data, function(k,v){
if(v.title.indexOf("carrot") in order){
order[v.title.indexOf("carrot")+1] = v.title;
} else {
order[v.title.indexOf("+ingred_val+")] = v.title;
}
});
data = order.clean(undefined); //remove undefined indexes from array
return {
results: $.map(data, function (item) {
return {
text: item.title,
id: item.id
}
})
};
}
Array.prototype.clean = function(deleteValue) {
for (var i = 0; i < this.length; i++) {
if (this[i] == deleteValue) {
this.splice(i, 1);
i--;
}
}
return this;
};
Update 3
$(document).ready(function(){
$('#RecipeIngredientId').on('change', function()
{
var ingred_val = $(this).val();
$('#RecipeIngredientId').select2({
$('#RecipeIngredientId').select2().change();
processResults: function (data) {
var order = [];
$.each(data, function(k,v){
if(v.title.indexOf(ingred_val) in order){
order[v.title.indexOf(ingred_val)+1] = v.title;
} else {
order[v.title.indexOf(ingred_val)] = v.title;
}
});
data = order.clean(undefined); //remove undefined indexes from array
return {
results: $.map(data, function (item) {
return {
text: item.title,
id: item.id
}
})
};
}
})
});
Array.prototype.clean = function(deleteValue) {
for (var i = 0; i < this.length; i++) {
if (this[i] == deleteValue) {
this.splice(i, 1);
i--;
}
}
return this;
};
});

Related

Sorting Array in nodejs by date order (recent to oldest)

I'm trying to sort the following array so that the most recent event_end is first
{
"results":[
{
"event_start":"2017-11-27T09:00:00Z",
"event_end":"2017-11-27T09:00:00Z",
"attendance":0,
"title":"Administrate Training Session",
"type":"delegate"
},
{
"event_start":"2018-02-01T09:00:00Z",
"event_end":"2018-02-01T09:00:00Z",
"attendance":0,
"title":"Health and Safety Awareness (HSA)",
"type":"delegate"
},
{
"event_start":"2018-02-19T09:00:00Z",
"event_end":"2018-04-30T09:00:00Z",
"attendance":0,
"title":"SMSTS",
"type":"delegate"
}
]
}
My current code (and this is after trying almost all the different ways to do this is):
Array.from(outcome).sort(sortFunction);
function sortFunction(a, b){
if(b[3] === a[3]){
return 0;
} else {
return (b[3] < a[3]) ? -1 : 1;
}
}
And just to give clarity to how the array is being created:
var history = JSON.parse(body);
var outcome = {};
var key = 'results';
outcome[key] = [];
history.forEach(delegate => {
var data = null;
var sessionKey;
var attendanceCount = 0;
var sessionCount = 0;
var attended = 0;
Array.from(delegate['session_attendance']).forEach(function(val){
if(!val.__proto__.__proto__){
sessionCount++;
}
});
var type;
for(var k in delegate['session_attendance']){
sessionKey = k;
if(k['status'] == true){
attendanceCount++;
}
}
if(attendanceCount == 0){
attended = attendanceCount;
} else {
(attendanceCount / sessionCount) * 100
}
if(delegate['registration']['booking_contact'] !== null){
if(delegate['registration']['booking_contact']['id'] == delegate['contact']['id']){
type = 'booking_contact';
}
} else{
type = 'delegate';
}
data = {
'objectId': delegate['id'],
'title': delegate['event']['title'],
'event_start': delegate['event']['start'],
'event_end': delegate['session_attendance'][sessionKey]['start'],
'attendance': attended,
'type': type
}
outcome[key].push(data);
})
I'm sure its obvious but can anyone point me in the direction of where I am going wrong and how to sort it appropriately?
var obj = {
"results":[
{
"event_start":"2017-11-27T09:00:00Z",
"event_end":"2017-11-27T09:00:00Z",
"attendance":0,
"title":"Administrate Training Session",
"type":"delegate"
},
{
"event_start":"2018-02-01T09:00:00Z",
"event_end":"2018-02-01T09:00:00Z",
"attendance":0,
"title":"Health and Safety Awareness (HSA)",
"type":"delegate"
},
{
"event_start":"2018-02-19T09:00:00Z",
"event_end":"2018-04-30T09:00:00Z",
"attendance":0,
"title":"SMSTS",
"type":"delegate"
}
]
}
obj.results.sort((a, b) => {
return new Date(b.event_end) - new Date(a.event_end)
})
console.log(obj.results)
The function that sort receives get 2 params, each param is an obj, so you can access its properties.
Something like this should work:
arr.sort((a, b) => {
return a.event_end > b.event_end ? -1 : 1;
})

Multiple Search function through array

I'm trying to search through a list of multiple values.
Here is the an example of the values:
[
{
"color":"blue",
"medium":"Sculpture",
"place":"Garage"
}
{
"color":"red",
"medium":"Painting",
"place":"Pool"
}
]
Below is my code. Works great to find a single value. But I need to find multiple values. For example I need to look and find the results for queries such as: "red blue" or "blue Painting".
It should return results that have both word.
I don't really know how to solve this, does anybody have an idea?
Thanks a lot
function search(){
var search = $('#search').val();
if(search.length < 1) {
return null;
};
var searches = search.split(" ");
var fields = ["color","medium","place"];
var results = [];
$.each(searches, function(i, word){
var wordResult = searchInJson(word,fields,json);
if( wordResult.length > 0 ) {
results.push(wordResult);
}
});
var results = searchInJson(searches,fields,json);
displaySearchResults(results);
};
function searchInJson(search,fields,json) {
var regex = new RegExp(search);
var results = [];
$.each(json, function(i, image){
$.each(fields, function(j, fieldname){
var field = image[fieldname];
if (regex.test(field)) {
results.push( image );
}
});
});
return results;
}
Here's a quick method to try:
var list = [
{
"color":"blue",
"medium":"Sculpture",
"place":"Garage"
},
{
"color":"red",
"medium":"Painting",
"place":"Pool"
}
];
var search = "red painting";
var results = list.filter(function (el) {
var s = search.toLowerCase().split(" ");
for (var key in el) {
for (var i=0; i < s.length; i++) {
if (el[key].toLowerCase() == s[i]) { // this could use indexOf depending on if you want to match partial words
s.splice(i,1);
i--;
if (!s.length) return true;
}
}
}
return false;
});
console.log(results);

Remove from Cart is not Working in AngularJS

Here is my code
$scope.cart = [];
$scope.addToCart = function (cat) {
var found = false;
$scope.cart.forEach(function (item) {
if (item.id === cat.product_id) {
item.quantity++;
found = true;
}
});
if (!found) {
$scope.cart.push(angular.extend({quantity: 1}, cat));
}
};
//remove from cart function
$scope.removeToCart = function (cat) {
console.log(cat.product_id);
var found = false;
$scope.cart.forEach(function (item) {
if (item.id === cat.product_id) {
item.quantity--;
found = true;
}
});
if (!found) {
$scope.cart.push(angular.extend({quantity: 1}, cat));
}
};
console.log($scope.cart);
$scope.getCartPrice = function () {
var total = 0;
$scope.cart.forEach(function (cat) {
total += cat.finalprice * cat.quantity;
});
return total;
};
Probably you need to remove this bit from your removeToCart function:
if (!found) {
$scope.cart.push(angular.extend({quantity: 1}, cat));
}
If "cat" is not found in the cart, you'll always add one with quantity of 1. Both "addToCart" and "removeToCart" seems identical for me, apart the item.quantity++ and item.quantity-- lines.

Filter multiple columns at the same time

Im using angularJS to create a list of items. Now I want to filter so that I can search in multiple columns at the same time. For example if I search for "Bob" all the columns containing "Bob" will show, and then I continue to search for "Bob 073" all columns containing the name "Bob" and the telephone-number that contains "073" will show.
I have created a filter that achieves something similar, but is hardcoded to specific columns and only works if I search for both columns.
app.filter('appFilter', function () {
return function (data, search) {
if (!search) {
return data;
} else {
var term = search;
var termsArray = term.split(' ');
return data.filter(function(item){
return item.name.indexOf(termsArray[0]) > -1 && item.phone.indexOf(termsArray[1]) > -1;
});
}
}
});
<input type="search" ng-model="search">
<div ng-repeat="item in items | appFilter:search )">
{{item.name}}, {{item.phone}}
</div>
I hope you understand what I mean.
Thanks.
myApp.filter('filterMultiple', ['$filter', function ($filter) {
return function (items, keyObj) {
var filterObj = {
data: items,
filteredData: [],
applyFilter: function (obj, key) {
var fData = [];
if (this.filteredData.length == 0)
this.filteredData = this.data;
if (obj) {
var fObj = {};
if (!angular.isArray(obj)) {
fObj[key] = obj;
fData = fData.concat($filter('filter')(this.filteredData, fObj));
} else if (angular.isArray(obj)) {
if (obj.length > 0) {
for (var i = 0; i < obj.length; i++) {
if (angular.isDefined(obj[i])) {
fObj[key] = obj[i];
fData = fData.concat($filter('filter')(this.filteredData, fObj));
}
}
}
}
if (fData.length > 0) {
this.filteredData = fData;
}
}
}
};
if (keyObj) {
angular.forEach(keyObj, function (obj, key) {
filterObj.applyFilter(obj, key);
});
}
return filterObj.filteredData;
}
}]);
Usage:
arrayOfObjectswithKeys | filterMultiple:{key1:['value1','value2','value3',...etc],key2:'value4',key3:[value5,value6,...etc]}

Accessing Data in the Json File

I am having hard time to access the particular json data. Here`s my json file
{
"id": "72",
"title": "Item Category Product Level Average Price Comparison",
"xLabel": null,
"yLabel": "Average Price",
"zLabel": null,
"data": [{
"avgPrice": "87",
"numProducts": "85"
}, {
"avgPrice": "60",
"numProducts": "49"
}, {
"avgPrice": "59",
"numProducts": "65"
}
I want to take the value of avgPrice and numProducts of the unique values first corresponding to the merchant name. For example In the json data, First and last merchantName is same(i.e "merchantName" : "A") . So I want to take the value of Merchant A first, and Merchant B(if it is repeated I want to complete that first and then go for the another Merchant.
var mn = [];
$.each(returnedData.data, function (index, value) {
if($.inArray(value.merchantName, mn) == -1) {
mn.push(value.merchantName);
}
});
//all the merchants name stored in mn[]
function get_items_by_merchant(merchant_name) {
var items = new Array();
$.each(returnedData.data, function (index, item) {
if(returnedData.merchantName == merchant_name)
items.push(item);
});
return items;
}
var CB_items = [];
for(var i = 0; i < mn.length; i++) {
CB_items[i] = get_items_by_merchant(mn[i]);
$.each(CB_items, function (index, item) {
var avgpricve = parseFloat(response.data[i].avgPrice);
var numproducts = parseFloat(response.data[i].numProducts);
datajson = {
x: avgpricve,
y: numproducts
}
result_data.push(datajson)
});
}
response is the data in json file, I am getting it using $.getJSON . In the above code I want to
access merchant name line response.data[i].mn[i].avgPrice.. Since that I am unable to.. Is there any way that I can do?
In the function get_items_by_merchant change this
$.each(returnedData.data, function(index, item) {
if (returnedData.merchantName == merchant_name) // There is not merchantName in returnedData.
items.push(item);
});
to
$.each(returnedData.data, function(index, item) {
if (item.merchantName == merchant_name)
items.push(item);
});
Final Code with changes:-
Demo
var result_data = [];
var mn = [];
$.each(returnedData.data, function (index, value) {
if ($.inArray(value.merchantName, mn) == -1) {
mn.push(value.merchantName);
}
});
//all the merchants name stored in mn[]
function get_items_by_merchant(merchant_name) {
var items = new Array();
$.each(returnedData.data, function (index, item) {
if (item.merchantName == merchant_name) items.push(item);
});
return items;
}
var CB_items = [];
for (var i = 0; i < mn.length; i++) {
CB_items[i] = get_items_by_merchant(mn[i]);
$.each(CB_items[i], function (index, item) {
var avgpricve = parseFloat(item.avgPrice);
var numproducts = parseFloat(item.numProducts);
datajson = {
x: avgpricve,
y: numproducts
}
result_data.push(datajson)
});
console.log(result_data)

Categories