Jquery Autocomplete matching multiple unordered words in a string - javascript

I am trying to show the best match of the search term typed in. For example
Right now Jquery does not give me the desired effect. When I type: one today the autocomplete will show nothing but if I type one day it will show the search results that start with those two words in that order. I want one today to show up one day is the first and last today. I want the search results to show up that have those words in them the ordering is not important. I have looked through here and could find nothing like this, it seems like such a common searching method I cannot see why no one has asked this question. Is there a built in method that handles this?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
var availableTags = [
"one day is the first and last today" , "tuesday is today" , "one" , "one day is tomorrow"
];
$( "#tags" ).autocomplete({
source: availableTags, multiple: true,
mustMatch: false
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
</body>
</html>

Try overriding the default filter logic provided by auto complete.
// Overrides the default autocomplete filter function to search for matched on atleast 1 word in each of the input term's words
$.ui.autocomplete.filter = function (array, terms) {
arrayOfTerms = terms.split(" ");
var term = $.map(arrayOfTerms, function (tm) {
return $.ui.autocomplete.escapeRegex(tm);
}).join('|');
var matcher = new RegExp("\\b" + term, "i");
return $.grep(array, function (value) {
return matcher.test(value.label || value.value || value);
});
};
Fiddle
Or create your own filter function and handle the search's return, so keeping complete's filter function as it is.
function customFilter(array, terms) {
arrayOfTerms = terms.split(" ");
var term = $.map(arrayOfTerms, function (tm) {
return $.ui.autocomplete.escapeRegex(tm);
}).join('|');
var matcher = new RegExp("\\b" + term, "i");
return $.grep(array, function (value) {
return matcher.test(value.label || value.value || value);
});
};
$("#tags").autocomplete({
source: availableTags,
multiple: true,
mustMatch: false
,source: function (request, response) {
response(customFilter(
availableTags, request.term));
},
});
Fiddle

Related

Using HTML5 local storage to store list items <ul>

I am creating a basic to-do list and was wondering on how to store my list so that when a user comes back to the page or accidentally refreshes the browser window, the list will still be available?
html
<!DOCTYPE html>
<html>
<head>
<title>My To-Do List</title>
<link rel="stylesheet" href="css/styles.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/font-awesome-animation.min.css">
<link href='https://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
<link rel="icon" href="/favicon.ico" type="image/x-icon">
</head>
<body>
<div id="page">
<header>
<img src="images/checklist.png" alt="some_text">
</header>
<h2>MY TO-DO LIST</h2>
<ul id="sortable"></ul>
<form id="newItemForm">
<input type="text" id="itemDescription" placeholder="Add Description" maxlength="40" />
<input type="submit" id="add" value="add" />
<div id="double">Drag and drop to rearrange items
<br />Click on an item to remove it</div>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="js/main.js"></script>
<script src="js/sort.js"></script>
<script src="jquery-ui/jquery-ui.js"></script>
</body>
</html>
JavaScript/jQuery
$(function () {
var $list;
var $newItemForm;
var $newItemButton;
var item = '';
$list = $('ul');
$newItemForm = $('#newItemForm');
$newItemButton = $('#newItemButton');
// ADDING A NEW LIST ITEM
$newItemForm.on('submit', function (e) {
e.preventDefault();
var text = $('input:text').val();
$list.append('<li>' + text + '</li>');
$('input:text').val('');
});
$list.on('click', 'li', function () {
var $this = $(this);
var complete = $this.hasClass('complete');
if (complete === true) {
$this.animate({}, 500, 'swing', function () {
$this.remove();
});
} else {
item = $this.text();
$this.remove();
}
});
});
localStorage.setItem($list);
//add animations when you learn how to...
You need to keep the data in an object also. Currently its only in DOM. Everything you add a new todo or edit an existing todo, you need to save that to the localstorage. Storing DOM nodes to localStorage wont work. localStorage also only accept string values.
So this is how I would change your code:
// localStorage key
var lsKey = 'TODO_LIST';
// keeping data
var todoList = {};
function getSavedData () {
var fromLs = localstorage.getItem( lsKey );
if ( !! fromLs ) {
todoList = JSON.parse( fromLs );
} else {
todoList = {};
localstorage.setItem( lsKey, todoList );
};
};
function saveData () {
var stringify = JSON.stringify( todoList );
localstorage.setItem( lsKey, todoList );
};
$newItemForm.on('submit', function(e) {
e.preventDefault();
var text = $('input:text').val().trim(),
uuid = new Date.now();
// lets use input[type:checkbox] to determine if complete or not
if ( !! text ) {
todoList[uuid] = text;
$list.append('<li><input type="checkbox" id=' + uuid + ' /> ' + text + '</li>');
$( 'input:text' ).val( '' );
};
};
$list.on('change', 'li input', function() {
var uuid = $(this).attr( 'id' ),
$li = $(this).parent();
if ( $(this).prop('checked') ) {
todoList[uuid] = undefined;
delete todoList[uuid];
saveData();
$li.fadeOut("slow", function() {
$this.remove();
};
};
});
Good luck, have fun!
You have to do 2 things: first is to store ony your data, not html. Second thing is that you have to provide a name for your item in localStorage because this is a key/value storage, so it needs a name for a key. Also because localStorage stores all data as a string value, call JSON.stringify() on your data before you sore it. So your code will be something like this: localStorage.setItem("yourKeyName", JSON.stringify(yourDataObj)). And when you want to read your data from it do JSON.parse(localStorage.getItem("yourKeyName")) to get your data as json object

Filtering JSON reply in jQuery

I'm attempting to filter out the reply I get from a JSON query to the Glosbe.com API.
Currently I've been able to break the JSON down to only receive the meanings but I'm unsure how to remove all of the commas and other aspects of the JSON response. I basically just want to display each meaning on a line of it's own.
jquery code:
$(document).ready(function(){
$('#term').focus(function(){
var full = $("#definition").has("definition").length ? true : false;
if(full === false){
$('#definition').empty();
}
});
var getDefinition = function(){
var word = $('#term').val();
if(word === ''){
$('#definition').html("<h2 class='loading'>We haven't forgotten to validate the form! Please enter a word.</h2>");
}
else {
$('#definition').html("<h2 class='loading'>Your definition is on its way!</h2>");
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=" +word+ "&pretty=true&callback=?", function(json) {
if (json !== "No definition has been found."){
var reply = JSON.stringify(json,null,"\t");
var n = reply.indexOf("meanings");
var sub = reply.substring(n+8,reply.length);
var subn = sub.indexOf("]");
sub = sub.substring(0,subn);
$('#definition').html('<h2 class="loading">We found you a definition!</h2> <h3>'+sub+'</h3>');
}
else {
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=rus&format=json&phrase=&pretty=true" + "?callback=?", function(json) {
console.log(json);
$('#definition').html('<h2 class="loading">Nothing found.</h2><img id="thedefinition" src=' + json.definition[0].image.url + ' />');
});
}
});
}
return false;
};
$('#search').click(getDefinition);
$('#term').keyup(function(event){
if(event.keyCode === 13){
getDefinition();
}
});
});
HTML page:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="author" content="Matthew Hughes">
<title>Dictionary Web Application</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script src="dictionary.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="container">
<header>
<h1>Dictionary Application</h1>
</header>
<section id="fetch">
<input type="text" placeholder="Enter a word..." id="term" />
<button id="search">Define!</button>
</section>
<section id="definition">
</section>
<footer>
<p>Created by Matthew & Spencer</p>
</footer>
</div>
Thanks.
JSON is JavaScript Object Notation. You can use it to send JavaScript objects around. You should take advantage of this, not flatten it and mess with string parsing.
Your json variable contains something like this:
{
...
"tuc": [
{
"authors": [
1
],
"meaningId": null,
"meanings": [
{
"language": "eng",
"text": "The process of applying a test as a means of analysis or diagnosis."
},
{
"language": "eng",
"text": "difficult, tough"
},
{
"language": "eng",
"text": "Present participle of test."
},
{
"language": "eng",
"text": "The act of conducting a test; trialing, proving"
}
]
},
...
]
}
You can access the section with the meanings with json["tuc"]; each of those contains an array of meanings (ie json["tuc"][0]["meanings"]). You can loop through each of those and extract the text property to build up your output.
For example, inside .getJSON, once you've verified that you do have data:
var meanings = "";
json["tuc"].forEach(function(tuc) {
tuc["meanings"].forEach(function(m) {
meanings += "<p>"+m["text"]+"</p>\n";
});
});
$("#definition").html(meanings);

Grabbing Name attribute of Tags/Tag in Rally

I have been looking at the rally Object model, but I can't figure out how to grab the Name attribute of a Defect's Tag.
I made sure to include Tag and Tags in my fetch statement. I am storing all the defects into an array of objects called defectsNEWDEFECTS[]
I can return a Tag object by doing this:
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags;
document.write(tagNEWDEFECTS);
which will return this:
[object Object]
But, I can't seem to get it to return the NAME of the tag.
I tried:
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags.Name;
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags.Tag.Name;
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tag.Name;
But they all return 'undefined'.
Any ideas how to get the name of a tag? Ultimately, the goal here is to have user-input custom tags that I can flag in my program to do certain things. For example, one tag will be named 'RollOverDefect'.
I need to be able to determine which Defects have a Tag called 'RollOverDefect'
Thanks!
Tags is a collection, so you'll ultimately need a nested loop over the Tags collection attribute to handle this. Once you've nested into an additional loop, you can reference the Tag Name via:
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags[j].Name;
Hope this is helpful - let us know if that gets the job done.
You may find this example to be useful:
<html>
<head>
<title>App Example: Defects with Tags</title>
<meta name="Name" content="App Example: Defects with Tags" />
<meta name="Version" content="2013.2" />
<meta name="Vendor" content="Rally Labs" />
<script type="text/javascript" src="/apps/1.33/sdk.js?apiVersion=1.43""></script>
<script type="text/javascript">
var table = null;
function defectsWithTagsExample() {
var rallyDataSource = new rally.sdk.data.RallyDataSource('__WORKSPACE_OID__',
'__PROJECT_OID__',
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__'
);
function itemQuery() {
var queryObject = {
key: 'defects',
type: 'Defect',
fetch: 'FormattedID,Name,State,Description,Tags,Name',
query: '(State = "Submitted")'
};
rallyDataSource.findAll(queryObject, populateTable);
}
function populateTable(results) {
if (table) {
table.destroy();
}
var tableDiv = document.getElementById('aDiv');
var config = {
'columnKeys' : ['FormattedID', 'Name', 'Description', 'State', 'Tags'],
'columnHeaders' : ['FormattedID', 'Name', 'Description', 'State', 'Tags'],
'columnWidths' : ['100px', '400px', '200px', '85px', '300px']
};
table = new rally.sdk.ui.Table(config);
table.addRows(results.defects);
for (i=0;i<results.defects.length;i++) {
myDefect = results.defects[i];
myTags = results.defects[i].Tags;
myTagString = "";
for (j=0;j<myTags.length;j++) {
myTag = myTags[j];
myTagName = myTags[j].Name;
if (j == 0) {
myTagString += myTagName;
} else {
myTagString += ", " + myTagName;
}
}
linkConfig = {item: {FormattedID: myDefect.FormattedID, "_ref" : myDefect._ref}};
defectLink = new rally.sdk.ui.basic.Link(linkConfig);
table.setCell(i, 0, defectLink.renderToHtml());
table.setCell(i, 4, myTagString);
}
table.display(tableDiv);
};
itemQuery();
}
rally.addOnLoad(defectsWithTagsExample);
</script>
</head>
<body>
<div id="aDiv"></div>
</body>
</html>

showing array values in list items - Jquery, Backbone.js

i am trying to output array values via a click using backbone view model, please advise how to output each array values on a separate line or maybe displaying each array value in a list item via jquery. Thanks :)
<!DOCTYPE html>
<head>
<meta charset=utf-8" />
<title>Test</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="backbone.js"></script>
</head>
<body>
<button>click</button>
<div class="ctype"></div>
<div class="cexperience"></div>
<script type="text/javascript">
var Job1 = Backbone.Model.extend({
defaults:{
type:'permanent',
experience:['html','css','php']
}
});
var myJob1 = new Job1();
var Jobview1 = Backbone.View.extend({
el:'button',
events:{
'click':'render'
},
render: function(){
var _type = myJob1.get('type');
var _experience = myJob1.get('experience');
$('div.ctype').html(_type);
$('div.cexperience').html(_experience);
return this
}
})
$(document).ready(function(e) {
var myJobview1 = new Jobview1();
});
</script>
</body>
</html>
_.each(_experience, function (key, value) {
var tmp = $('<p />');
tmp.html(value);
$('.experience').append(tmp);
)};
this should work.
maybe you need to switch key, value to value, key.
i tend to forget the order of the parameters.

jquery autocomplete highlighting

How can I make my jquery autocomplete highlight what the user is typing in in any autocompleted results? The code I am using is:
$("#keyword").autocomplete({
source: "ajax/autocomplete.php?action=keyword",
minLength: 2
});
Tried this implemented from the link tomasz posted:
$("#keyword").autocomplete({
source: "ajax/autocomplete.php?action=keyword",
highlight: function(value, term) {
return value.replace(new RegExp("("+term+")", "gi"),'<b>$1</b>');
},
minLength: 2
});
No luck there either. jQuery autocomplete seems to hate me.
Update: Thanks to David Murdoch, I now have an answer! See #Herman's copy of the answer below.
Thanks goes to David Murdoch at http://www.vervestudios.co/ for providing this useful answer:
$.ui.autocomplete.prototype._renderItem = function( ul, item){
var term = this.term.split(' ').join('|');
var re = new RegExp("(" + term + ")", "gi") ;
var t = item.label.replace(re,"<b>$1</b>");
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + t + "</a>" )
.appendTo( ul );
};
$("#keyword").autocomplete({
source: "ajax/autocomplete.php?action=keyword",
minLength: 2
});
Thought somone might find this useful. it's a complete HTML doc that makes uses of the above principles. I used it as a protoype for some of my work.
<html xmlns="http://www.w3.org/1999/xhtml">
<!--
orders.html simply returns the following text
Basketball#Football#Baseball#Helicopter#gubbins#harry potter#banyan
-->
<head id="Head1" runat="server">
<title>AutoComplete Box with jQuery</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
function loadData() {
var sURL = "orders.htm";
$.ajaxSetup({ cache: false });
$.ui.autocomplete.prototype._renderItem = function (ul, item) {
var term = this.term.split(' ').join('|');
var re = new RegExp("(" + term + ")", "gi");
var t = item.label.replace(re, "<b>$1</b>");
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + t + "</a>")
.appendTo(ul);
};
$.get(sURL, function (responseText) {
data = responseText.split('#');
$("#txtSearch").autocomplete({
//source: availableSports
source: data,
minLength: 2
});
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">
Enter data:
</label>
<input type="text" id="txtSearch" class="autosuggest" onkeyup="loadData();" />
</div>
</form>
</body>
</html>
Hopefully it'll help someone as it helped me.

Categories

Resources