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.
Related
As I try to use the typo.js spell checker in my file. But it's throw some error's I can't find the solutions. I just followed the Typo.js Documentation Here is the document link.
https://github.com/cfinke/Typo.js/
Kindly check the below issue and help me to reach out this issue
Here is the console issue image
Here is the used code
JS
<!doctype html>
<html>
<head>
<title>Typo.js Example</title>
<meta charset="UTF-8" />
<script type="text/javascript" src="typo/typo.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
var dictionary = new Typo("en_US", false, false, { dictionaryPath: "typo/dictionaries" });
// function load() {
// $('#loading-progress').append('Loading affix data...').append($('<br />'));
// $.get('typo/dictionaries/en_US/en_US.aff', function (affData) {
// $('#loading-progress').append('Loading English dictionary (this takes a few seconds)...').append($('<br />'));
// $.get('typo/dictionaries/en_US/en_US.dic', function (wordsData) {
// $('#loading-progress').append('Initializing Typo...');
// dictionary = new Typo("en_US", affData, wordsData);
// checkWord('mispelled');
// });
// });
// }
checkWord('mispelled');
function checkWord(word) {
var wordForm = $('#word-form');
wordForm.hide();
var resultsContainer = $('#results');
resultsContainer.html('');
resultsContainer.append($('<p>').text("Is '" + word + "' spelled correctly?"));
var is_spelled_correctly = dictionary.check(word);
resultsContainer.append($('<p>').append($('<code>').text(is_spelled_correctly ? 'yes' : 'no')));
if (!is_spelled_correctly) {
resultsContainer.append($('<p>').text("Finding spelling suggestions for '" + word + "'..."));
var array_of_suggestions = dictionary.suggest(word);
resultsContainer.append($('<p>').append($('<code>').text(array_of_suggestions.join(', '))));
}
wordForm.show();
}
</script>
</head>
<body>
<h1>Typo.js Demo</h1>
<p>This page is an example of how you could use Typo.js in a webpage
if you need spellchecking beyond what the OS provides.</p>
<p id="loading-progress"></p>
<div id="results"></div>
<form method="GET" action="" onsubmit="checkWord( document.getElementById( 'word' ).value ); return false;"
id="word-form" style="display: none;">
<p>Try another word:</p>
<input type="text" id="word" value="mispelled" />
<input type="submit" value="Spellcheck" />
</form>
</body>
</html>
I have a JS function to make textbox operation. When I sent textbox client ID, I am receiving this syntax error:
JavaScript runtime error: Syntax error, unrecognized expression: #<%=txtEposta.ClientID%>
How can I fix this error? I am very new to JavaScript. Whatever I tried I cannot find a solution. Please help.
function SearchText(clientID) {
console.log("#" + clientID);
var availableTags = ["gmail.com", "hotmail.com", "mynet.com", "yahoo.com", "outlook.com", "windowslive.com"];
$("#"+clientID).autocomplete({
source: availableTags,
matchCase: false,
focus: function (event, ui) {
var oldValue = $("#" + clientID).val();
var value = oldValue + ui.item.value;
event.preventDefault();
$("#" + clientID).val(value);
},
select: function (event, ui) {
var oldValue = $("#" + clientID).val();
var value = oldValue + ui.item.value;
$("#" + clientID).val(oldValue);
event.preventDefault();
},
minLength: 0
});
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="TextBoxControl.WebUserControl1" %>
<link href="/Script/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.24.js"></script>>
<script type="text/javascript" src="../common.js"></script>>
<div>
<asp:Textbox runat="server" ID="txtEposta" MaxLength="100" Width="250px" onKeyPress="javascript:SearchText('<%=txtEposta.ClientID%>');"
ControlType="AlpfaNumericAndSymbols" AllowSpaces="False" Visible="true"></asp:Textbox>
</div>
You could simply replace the txtEposta.ClientID with this.
<asp:Textbox runat="server" ID="txtEposta" onKeyPress="javascript:SearchText(this);"
<script>
function SearchText(element) {
alert(element.id);
}
</script>
If you really want to use ClientID you will have to add it programatically
<asp:TextBox runat="server" ID="txtEposta"></asp:TextBox>
<script>
function SearchText(element) {
alert(element);
}
</script>
and then in Page_Load
txtEposta.Attributes.Add("onKeyPress", string.Format("javascript:SearchText('{0}');", txtEposta.ClientID));
Set the property ClientIDMode in you Textbox to Static. Thes will make the ClientID be the same as the id on server side. Don't forget to change the onKeyPress argument.
<asp:Textbox runat="server" ID="txtEposta" ClientIDMode="Statis" MaxLength="100" Width="250px" onKeyPress="javascript:SearchText('txtEposta');"
ControlType="AlpfaNumericAndSymbols" AllowSpaces="False" Visible="true"></asp:Textbox>
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
this is my AutoComplete code :
<link href="JostejuFile/css/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
<script src="JostejuFile/scripts/jquery-1.4.1.min.js"></script>
<script src="JostejuFile/scripts/jquery.autocomplete.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtSearch.ClientID%>").autocomplete("Handler/Search_CS.ashx", {
width: 200,
formatItem: function (data, i, n, value) {
return "<img style = 'width:50px;height:50px' src='PRupload/" +
value.split("-")[1] + "'/>" + value.split("-")[0];
},
formatResult: function (data, value) {
return value.split("-")[0];
}
});
});
</script>
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
I want to fire an event on the click or selection of an item from the autocomplete list.Can anyone please help me out with this?
You can always add code for select event in autocomplete:
i.e.
$( ".selector" ).autocomplete({
select: function( event, ui ) {}
});
Reference:
http://api.jqueryui.com/autocomplete/#event-select
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