Displaying clean results of autocomplete [duplicate] - javascript

This question already has answers here:
jQuery UI Autocomplete use startsWith
(6 answers)
Closed 3 years ago.
I found this code online that gives options for autocomplete and I would like to give the options which start the key in letters. For example, if the alphabet 'a' is keyed in, I just want to give options start with 'a' not the options contain 'a', so from the code, when I key in 'a', I only want to display apple, not pineapples. How can I do that?
var x = [
{ label : 'apple', value : 'Delicious' },
{ label : 'pineapples', value : 'Delicious' },
{ label : 'kiwi', value : 'Yummy' },
{ label : 'kiwiooo', value : 'aaa' },
{ label : 'lemon', value : 'Sour' }
];
$( "#fruit" ).autocomplete({
source: x,
focus : function(){ return false; }}).on( 'autocompleteselect',
function( e, ui ){
var t = $(this),
details = $('#taste'),
label = ( e.type == 'autocompleteresponse' ? ui.content[0].label :
ui.item.label ),
value = ( e.type == 'autocompleteresponse' ? ui.content[0].value :
ui.item.value );
t.val( label );
details.val( value );
return false;});

The solution is pretty easy. I found the filter method used just for that. All that needs to be done is replacing that function with this:
// Overrides the default autocomplete filter function to and find only from the beginning of the string
<script>
$("#fruit").autocomplete({ source: function(request, response) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(myArray, function(item){
return matcher.test(item);
}));
}
});
</script>
There is another solution which i have used before.
source: function(request, response) {
var filteredArray = $.map(orignalArray, function(item) {
if( item.value.startsWith(request.term)){
return item;
}
else{
return null;
}
});
response(filteredArray);
}

Related

Using DataTables and extend excelHtml5 via JavaScript, how can I insert an image in the "title" property?

Excel Header
Legend
buttons: [
{
            extend: 'excelHtml5',
            text: '<h2>EXPORT TO EXCEL</h2>', //'Export to Excel',
//orientation: 'landscape',
//pageSize: '11x17',
title: 'Hello',
messageTop: function () {
var today = new Date();
I am using Datatables and the excelHtml5 button extension via Javascript & jQuery. You will see in the beginning of the code the text "Hello" in the title property. I am also using messageTop, customize, and createEmptyCells for other formatting purposes. In the attachment you will see the resulting "Hello" text circled in red.
I need to insert a legend image (.png) on the top. Is there any way to do this? Alternatively, if I cannot get in image in the title property I could format each cell of the title to look like the legend but I am not sure how to do this in the title property?
I was thinking along the lines of...
title: function() {
var imgProcessMap = $("#imgProcessMap");
return imgProcessMap;
},
...but this returns the object.
I was stuck on this like one week, I found this article and it was so useful for me.
Source: https://quo.wtf/posts/datatable_howto_export_excel_with_image/
You need to modify buttons.html5.js, and change xlsx and excelStrings variables basic structure to a new one. Then, use JQuery Datatables customize to send the image.
But, it doesn't work. I realize you have to modify _addToZip function in buttons.html5.js to add the image with jszip, and an aditional validation.
Here's full _addToZip code.
function _addToZip( zip, obj ) {
if ( _ieExcel === undefined ) {
// Detect if we are dealing with IE's _awful_ serialiser by seeing if it
// drop attributes
_ieExcel = _serialiser
.serializeToString(
( new window.DOMParser() ).parseFromString( excelStrings['xl/worksheets/sheet1.xml'], 'text/xml' )
)
.indexOf( 'xmlns:r' ) === -1;
}
$.each( obj, function ( name, val ) {
if ( $.isPlainObject( val ) ) {
var newDir = zip.folder( name );
_addToZip( newDir, val );
}
else if (!$.isXMLDoc(val)){
var newDir = zip.folder(name);
newDir.file(val[0].name, val[0].data, {base64: true});
}
else {
if ( _ieExcel ) {
// IE's XML serialiser will drop some name space attributes from
// from the root node, so we need to save them. Do this by
// replacing the namespace nodes with a regular attribute that
// we convert back when serialised. Edge does not have this
// issue
var worksheet = val.childNodes[0];
var i, ien;
var attrs = [];
for ( i=worksheet.attributes.length-1 ; i>=0 ; i-- ) {
var attrName = worksheet.attributes[i].nodeName;
var attrValue = worksheet.attributes[i].nodeValue;
if ( attrName.indexOf( ':' ) !== -1 ) {
attrs.push( { name: attrName, value: attrValue } );
worksheet.removeAttribute( attrName );
}
}
for ( i=0, ien=attrs.length ; i<ien ; i++ ) {
var attr = val.createAttribute( attrs[i].name.replace( ':', '_dt_b_namespace_token_' ) );
attr.value = attrs[i].value;
worksheet.setAttributeNode( attr );
}
}
var str = _serialiser.serializeToString(val);
// Fix IE's XML
if ( _ieExcel ) {
// IE doesn't include the XML declaration
if ( str.indexOf( '<?xml' ) === -1 ) {
str = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+str;
}
// Return namespace attributes to being as such
str = str.replace( /_dt_b_namespace_token_/g, ':' );
// Remove testing name space that IE puts into the space preserve attr
str = str.replace( /xmlns:NS[\d]+="" NS[\d]+:/g, '' );
}
// Safari, IE and Edge will put empty name space attributes onto
// various elements making them useless. This strips them out
str = str.replace( /<([^<>]*?) xmlns=""([^<>]*?)>/g, '<$1 $2>' );
zip.file( name, str );
}
} );
}
Sorry for my english, hope this helps.

How to get values in Json Array and use each of them separately

I have a JSON and I Want to separate each field of that in array part and then I want to use of each field separately and put them in separate array.
for example I have two part in my array and I want to divide the first part too room 1 and second part in room 2 .
I have to send Json to my second page with format room1 and room 2. and I do not know how can I do this
my json is like this right now :
"rooms": [
{
"adultcount": "1",
"childcount": "1,1"
},
{
"adultcount": "1",
"childcountandage": "0 "
}
]
but I want to change it like this :
"rooms": [
{
"rooms1": {
"adultcount": "1",
"childcount": "1,1"
}
},
{
"rooms2": {
"adultcount": "2",
"childcount": "10,1"
}
}
]
then I need to use them.
how can I do this with jquery ?
there is no need to change the json code I just wrote the sample the new json to define better.
here is my code :
$( document ).ready(function() {
var research={"rooms":[{ "adultcount":"1","childcount":"1,1" },{ "adultcount":"1","childcountandage":"0 " }] }
var adultcount = research.rooms[0].adultcount;
var childcount = research.rooms[0].childcount;
});
Since you have an array that you want to make into an object and the property name seems to be the index inside the array, you can use a basic array.reduce:
var rooms = [
{ "adultcount":"1", "childcount":"1,1" },
{ "adultcount":"2", "childcount":"10,1" }
];
var roomsMap = rooms.reduce( function( map, room, index ) {
map[ 'room' + ( index + 1 ) ] = room;
return map;
}, {} );
var otherRoomsMap = rooms.map( function( room, index ) {
var wrapper = {};
wrapper[ 'room' + ( index + 1 ) ] = room;
return wrapper;
} );
console.log( roomsMap );
console.log( otherRoomsMap );
edit:
I have added the other example of keeping the array and just wrapping the objects isnide another object, but I have no idea what advantage that would give over the original array.
You can access your json array using loop
$.each(research, function (key, value) {
var adultcount = value.adultcount;
var childcount = value.childcount;
console.log("Adult count is:"+value.adultcount);
console.log("Child count is:"+value.childcount);
});
Try this:
var research={"rooms":[{ "adultcount":"1","childcount":"1,1" },{"adultcount":"1","childcountandage":"0 " }] };
var newResearch = {"rooms": []};
research.rooms.forEach(function(r) {
newResearch.rooms.push({"room1": r[0], "room2": r[1]});
});
console.log(newResearch);

How can I get object by key? [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 7 years ago.
var test = [
{
id : 'user01',
pos0 : 2
},
{
id : 'user01',
pos0 : 3
},
{
id : 'user02',
pos1 : 5
},
{
id : 'user02',
pos1 : 6
},
{
id : 'user03',
pos2 : 8
},
{
id : 'user03',
pos2 : 9
}
]
This is example data,
and
I want if I passed 'pos2', get test[4] and test[5].
//like this :
function getObjectByKey(array, key){
// dosomething
};
..
var testArray = getObjectByKet(test, 'pos2');
I tried to use $.inArray or $.map, but how to use them.
How can i do this?
Regards.
Please try this,
function getObjectByKey(array, key){
var users=[];
$.map(array, function (user, index) {
if (user[key])
users.push(user)
});
return users;
};
hope this will help you.
Also change your function calling. You miss spelled the function name
Try this while calling the method
var testArray = getObjectByKey(test, 'pos2');
I would suggest to use Array.prototype.map() method to iterate an array. Like this:
var test = [
{
id : 'user01',
pos0 : 2
},
{
id : 'user01',
pos0 : 3
},
{
id : 'user02',
pos1 : 5
},
{
id : 'user02',
pos1 : 6
},
{
id : 'user03',
pos2 : 8
},
{
id : 'user03',
pos2 : 9
}
]
var user;
test.map(function(v) { if(v.id == 'user03') user = v; });
Here is a FIDDLE.

Issue Pushing values in to objects Javascript

Have some issue with push the values in to the javascript array object. Please any one give me the perfect solution
Class code :
var myfuns = ( function(undefined) {
var myarr ={};
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
}
}
function _getList() {
return $.extend(true, {}, myarr);
}
return {
add : _add,
getList : _getList
}
}());
Here am calling and manage the values and keys
function setmydetails(){
var my_param = {
current_info : {
pg : '#tset',
no : 12,
name : "john",
row : 0,
},
userprofile : [],
class : [],
marks : [],
games : []
};
myfuns.add(my_param);
}
Now i got the array
myfuns.getList() // GOT proper array what i passed in my_param
Question : How to modify the existing values from any one of the Inner array from the myarr Obj
Ex: Once First array created later have to modify some from "myarr.current" = > Change current_info.row to 2222
Similar i have to add some array in to " myarr.class " etc
I would like to say try this one not tested
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
$.extend( myarr.current, arrayparam);
}
}
proper source : https://api.jquery.com/jquery.extend/

jqueryui autocomplete how to pass in an array of keywords to search through for each object?

I'm trying to use jQueryUI Autocomplete to implement a site quick searching feature for various functionality pages in my site. So when they search for "create" it will bring up the Create user option and the Create organisation option. When they search for "create u" it will only show the Create User option. These are just some of the links. But as you can see, each page will have some various keywords/synonyms that would all point to the same page.
Basically I want a structure like this:
var links = [
{
keywords: ['create', 'add', 'make', 'insert', 'user'],
label: "Create user",
desc: "Create a user in the system",
url: 'http://mysite.com/user/create/'
},
{
keywords: ['create', 'add', 'make', 'insert', 'organisation'],
label: "Create organisation",
desc: "Create an organisation in the system",
url: 'http://mysite.com/organisation/create/'
}];
So as they're typing it should look up the links array then search through the keywords arrays looking for a partial text match based on what they've typed in. If it finds one then it will show that entry in the auto completer. But if the second or third search word doesn't match any of the keywords then it will not show it.
Now I've heard you may be able to do it by supplying the source as a callback?
Here's my code so far (Edit: updated with working solution):
var links = [
{
keywords: ['create', 'add', 'make', 'insert', 'user'],
label: "Create user",
desc: "Create a user in the system",
url: 'http://mysite.com/user/create/'
},
{
keywords: ['create', 'add', 'make', 'insert', 'organisation'],
label: "Create organisation",
desc: "Create an organisation in the system",
url: 'http://mysite.com/organisation/create/'
}];
$("#searchTerms").autocomplete(
{
minLength: 2,
source: function(request, response)
{
var matched = [];
// Get entered search terms (request.term) from user and search through all links keywords
for (var k = 0; k < links.length; k++)
{
// If it matches, push the object into a new array
if (checkSearchWordsMatchKeywords(request.term, links[k]['keywords']))
{
matched.push(links[k]);
}
}
// Display the filtered results
response(matched);
},
focus: function( event, ui )
{
$( "#searchTerms" ).val( ui.item.label );
return false;
},
select: function( event, ui )
{
// Redirect to the url
$( "#searchTerms" ).val( ui.item.label );
window.location.replace(ui.item.url);
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( '<b>' + item.label + '</b><br>' + item.desc + '' )
.appendTo( ul );
};
/**
* Check that each word in a search string matches at least one keyword in an array
* E.g. searchWords = 'create use' and keywords = ['create', 'add', 'make', 'insert', 'user'] will return true
*/
function checkSearchWordsMatchKeywords(searchWords, keywords)
{
var searchWords = searchWords.toLowerCase(); // Lowercase the search words
var searchWords = searchWords.split(' '); // Break up the search into separate words
var numOfSearchWords = searchWords.length; // Count number of search words
var numOfKeywords = keywords.length; // Count the number of keywords
var matches = []; // Will contain the keywords that matched the search words
// For each search word look up the keywords array to see if the search word partially matches the keyword
for (var i = 0; i < numOfSearchWords; i++)
{
// For each keyword
for (var j = 0; j < numOfKeywords; j++)
{
// Check search word is part of a keyword
if (keywords[j].indexOf(searchWords[i]) != -1)
{
// Found match, store match, then look for next search word
matches.push(keywords[j]);
break;
}
}
}
// Count the number of matches, and if it equals the number of search words then the search words match the keywords
if (matches.length == numOfSearchWords)
{
return true;
}
return false;
}
});
Ok so the checkSearchWordsMatchKeywords function at the end there definitely works because I've tested it. What isn't working is I don't know what I'm supposed to return from the jQueryUI search: function.
Any help please?
I run over this issue at work. In order to fix it we created our own search function. In order to search in the keywords even if they are in the actual string you want to display.
$( "#searchTerms" ).autocomplete({
search: function(event, ui) {
// Add your super search function here
}
});

Categories

Resources