From Jquery-ui autocomplete to typeahead.js - jquery-ui

I am migrating my app to twitter-bootstrap and i would like to replace my jquery-ui autocomplete with typeahead.js.
It would be better to use the feature embedded in twitter-bootstrap but i am ok with the extra typeahead plugin if necessary.
My problem is that i have trouble reproducing the current behaviour especially with the absence of results.
How would you do something like that?
$("#search").autocomplete({
source : myUrl,
delay : 100,
minLength : 2,
select : function(event, ui) {
// do whatever i want with the selected item
},
response : function(event, ui) {
if (ui.content.length === 0) {
ui.content.push({
label : "No result",
value : customValue
});
}
}
});
Basically, if there is no result, i want to display a custom message in the component.
Thanks!

The migration to Bootstrap typeahead would look something like..
$('.typeahead').typeahead({
minLength:2,
updater: function (item) {
/* do whatever you want with the selected item */
},
source: function (typeahead, query) {
/* put your ajax call here..
return $.get('/typeahead', { query: query }, function (data) {
return typeahead.process(data);
});
*/
}
});
EDIT:
I've updated the demo to include a sorter and highlighter. I think this will get you the results you want..
sorter: function(items) {
if (items.length == 0) {
var noResult = new Object();
items.push(noResult);
}
return items;
},
highlighter: function(item) {
if (dataSource.indexOf(item) == -1) {
return "<span>No Match Found.</span>";
}
else {
return "<span>"+item+"</span>";
}
},
Bootstrap Typeahead Demo
I don't think the typeahead has an equivalent to delay, but there are some jquery workarounds for this.

With the latest version of Typeahead.js (0.10) it is now possible to specify an empty template to display when no results are found.
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 2
},{
name: 'examples',
source: examples.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'unable to find any results that match the current query',
'</div>'
].join('\n')
}
});

Related

JqGrid searchoptions with select2 existing value

I'm trying to integrate select2 for JqGrid filter form. I'm using JqGrid min 4.6 & Select2 min 4.0.1. The filter works fine but I'm unable to retrieve the value that has been set through select2 once the filter form is closed and reopened. i.e. dataInit e1 does not return the existing value of the select input. I must be doing something wrong?
JqGrid Column Model:
{
name: 'CurrencyID', hidden: true, search: true, stype: 'select', searchtype: 'number', searchoptions: {
searchhidden: true,
sopt: ['eq', 'ne'],
dataInit: function (el) {
intiGridFilterSelecr2Field(el, paramFromView.CurrencyOptions);
}
},
searchrules: { required: true }
},
Parameters:
#section scripts{
<script>
var paramFromView = {
CurrencyOptions: {
searchURL: '#Url.Action("GetCurrency", "Controller")',
detailURL: '#Url.Action("CurrencyDetailsJson", "Controller")',
idField: 'CurrencyID',
txtField: 'Description'
}
};
</script>
}
Select2 Helper:
function intiGridFilterSelecr2Field(element, options) {
var comboPageSize = 15;
var quietMillis = 200;
var placeHolderText = 'Choose...'
var defaults = {
searchURL: '',
detailURL: '',
idField: '',
txtField: ''
};
var options = $.extend({}, defaults, options);
var select2Element = $(element);
select2Element.select2({
width: 'element',
minimumInputLength: 1,
placeholder: placeHolderText,
ajax: {
url: options.searchURL,
dataType: 'json',
quietMillis: quietMillis,
cache: false,
data: function (params) {
return {
name: params.term,
page: params.page,
pageSize: comboPageSize
};
},
processResults: function (data) {
var more = (data.page * comboPageSize) < data.total;
var resultsArr = [];
for (var i = 0; i < data.result.length; i++) {
resultsArr.push({ id: data.result[i][options.idField], text: data.result[i][options.txtField] });
}
return { results: resultsArr, more: more };
}
},
}).each(function (index, element) {
var idCombo = $(this);
// The problem is that idCombo.val() is always empty.
// element:select2-hidden-accessible
if (idCombo.val() != null && idCombo.val().length > 0) {
$.ajax(options.detailURL, {
data: {
id: idCombo.val()
},
dataType: 'json',
cache: false
}).done(function (data) {
var optselected = select2Element.find('option').filter(function () { return this.value == data[idField] && this.text == data[txtField] && this.selected })
if (optselected == undefined || optselected.length == 0) {
var $optionContact = $("<option selected></option>").val(data[idField].toString()).text(data[txtField]);
var toBeRemoved = select2Element.find('option').filter(function () { return this.value == data[idField] });
if (toBeRemoved != undefined) {
toBeRemoved.remove();
}
select2Element.append($optionContact).trigger('change.select2');
}
});
}
});
}
When the filter is being set...
When Loading the existing filter. How do I pass this CurrencyID = 1 to select2 helper?
Update:
With Oleg's answer, I updated my code as below.
{
name: 'CurrencyID', hidden: true, searchtype: 'number', search: true,
stype: "select", searchoptions: {
searchhidden: true,
sopt: ["eq", "ne"],
dataUrl: paramFromView.CurrencyOptions.searchURL,
buildSelect: function (data) {
var obj = jQuery.parseJSON(data);
var i, options = [];
for (i = 0; i < obj.result.length; i++) {
options.push("<option value='" + obj.result[i][paramFromView.CurrencyOptions.idField] + "'>" +
obj.result[i][paramFromView.CurrencyOptions.txtField] + "</option>");
}
return "<select>" + options.join("") + "</select>";
},
noFilterText: "Any",
selectFilled: function (options) {
setTimeout(function () {
$(options.elem).select2({
width: 'element',
});
}, 0);
}
},
searchrules: { required: true }
},
I'm almost there with what I wanted to achieve. However I'm still facing some difficulties.
When the filter is initially loaded, value is selected on the dropdown but query value is empty. i.e. if the user clicks on the find button soon after the filter form is loaded, no filter will be set.
I still cannot get select2 styles working.
I can demonstrate how to use select2 with free jqGrid fork of jqGrid, which I develop. I get the demo from the README of the old version 4.14.1 (the current released version is 4.15.3) and modified it to demonstrate the usage of select2.
The main part of the code could be
stype: "select",
searchoptions: {
sopt: ["eq", "ne"],
...
selectFilled: function (options) {
setTimeout(function () {
$(options.elem).select2({
width: "100%"
});
}, 0);
}
}
See https://jsfiddle.net/Lae6kee7/2/. You can try to choose an option in the filter toolbar in "Shipped via" column and the open the search dialog. You will see that the select2 will have the same option selected.
If you would load the data via Ajax request posted by select2 than your code will be much more complex as it could be. It's important to understand that such way is really required only for really large set of possible value. I means the number of items larger as 100000 items for example. On the other side, the most use cases required less as 1000 options. In the case it would be more effective to load all the data as options of select and then convert the select to select2. select2, which uses local select works much more quickly from the users point of view.
The code will be easier in my opinion if you will use dataUrl instead of ajax option of select2. You can use dataUrl to return from the server all different values, which can be used in select2 and to use buildSelect to build <select> from JSON data returned from the server. The demo https://jsfiddle.net/Lae6kee7/23/ demonstrates that. I made the demo for JSFiddle, which supports Echo service (see here), which allows to simulate server responses. Your real code should contains mostly only dataUrl, buildSelect and the code of selectFilled, which I included above.
Additionally, I'd recommend you to consider to use <datalist> (see here for example), which could be good alternative to select2. All modern web browsers contains native support of <datalist> and thus <datalist> works very quickly. Try to search in the first Client column of my demos. You will see control, which will be very close to select2. Additional advantage of <datalist>: one will be able not search for only exact predefined values like test10, test11 or test12, but for substrings like 1. Compare
with
or
with

How to validate select with JQuery.Validate while using JQueryMobile

I'm just exploring the Validate plug-in for JQuery. During implementing in my webapp made with JQueryMobile I stumbled over the fact that validating such an element is not so simple like usual input-elements.
So the Question is: How to enable validation for select?
The trick consists out of two parts:
Validate is by default ignoring :hidden. But that's what JQM does with an <select>: hide it and placing a div-span-wrapper on top. Solution is to redefine the ignore-selector:
{ignore: ":hidden:not(select)"}
To inform the user about the invalid field you have to show the error right on the wrapper:
$(error.element).closest('.ui-select').attr("title", error.message).addClass("invalidInput")
And now in an working example:
$.validator.setDefaults({
debug: true,
ignore: ":hidden:not(select)",
submitHandler: function() { alert("submitted!"); },
showErrors: function(map, list) {
$(this.currentElements).each(function() {
if(this.nodeName == "SELECT") {
$(this).closest('.ui-select').removeAttr("title").removeClass("invalidInput");
return true;
}
$(this).removeAttr("title").removeClass("invalidInput");
});
$.each(list, function(index, error) {
if(error.element.nodeName == "SELECT") {
$(error.element).closest('.ui-select').attr("title", error.message).addClass("invalidInput");
return true;
}
$(error.element).attr("title", error.message).addClass("invalidInput");
});
}
});
$('div[data-role="page"]').bind('pageinit', function(event) {
var rules = {};
$('input:not(:button)').each(function() {
rules[this.name] = {required:true};
});
$('#fzgherst').each(function() {
// revalidates the select when changed, other elements gets revalidatet onblur
$(this).on('change', function() {$(this).valid();});
rules[this.name] = {required:true};
});
$("form").validate({
rules: rules
});
});
That's all folks!

AngularJS - jQuery UI - binding issue

I am currently porting a large application over to a HTML5 based web app - I have started building the app in AngularJS and enjoying the power of the AngularJS framework - I have one issue standing in my way currently:
I have a directive that gives me a jQuery Datepicker however the binding to the model does not seem to be working.
http://jsfiddle.net/9BRNf/
I am probably misunderstanding the way directives work and would like to see if I can patch this part of my understanding of the framework. I have gone through loads of examples (including the angularui project on github but still not making sense of why the binding is not happening)
any assistance will be greatly appreciated.
For those Googling this issue (as I was), a simpler way of tying in the jQuery UI datepicker with Angular is to do this...
$.datepicker.setDefaults({
// When a date is selected from the picker
onSelect: function(newValue) {
if (window.angular && angular.element)
// Update the angular model
angular.element(this).controller("ngModel").$setViewValue(newValue);
}
});
Just place it prior to your .datepicker() initialisation code.
(Taken from another answer I posted here: https://stackoverflow.com/a/17206242/195835)
First off, it's great that you are using angularjs, its a sweet framework. An offshoot project was started awhile back to deal with things like wrapping jquery-ui and creating ui modules.
Below is link to Peter Bacon Darwin's implementation.
https://github.com/angular-ui/angular-ui/tree/master/modules/directives/date
--dan
The angular-ui datepicker wasn't working with Angular 1.0.0, so I rewrote it. My fork gives you the ability to set how the date is formatted inside the input and how it gets saved back to the model.
Code: https://gist.github.com/2967979
jsFiddle: http://jsfiddle.net/m8L8Y/8/ (It's missing jquery-ui styles but works just the same)
// Code inspired by angular-ui https://github.com/angular-ui/angular-ui/blob/master/modules/directives/date/src/date.js
/*
Features:
* via the ui-date attribute:
* Ability to say how model is parsed into a date object
* Ability to say how input's value is parsed into a date object
* Ability to say how a date object is saved to the model
* Ability to say how a date object is displayed in the input
* via the ui-date-picker attribute
* Ability to directly configure the jQuery-ui datepicker
*/
angular.module('ui.directives', [])
.directive('uiDate', function () {
return {
require: '?ngModel',
//scope: {},
link: function ($scope, element, attrs, ngModel) {
// Date Handling Functions
var dateHandler = $.extend({ model: {}, view: {} }, $scope.$eval(attrs.uiDate));
// This will attempt to use preferredParser to parse a date.
function defaultDateParse(date, preferredParser) {
if (!preferredParser)
return new Date(date);
return preferredParser(date);
}
// This will attempt to use preferredFormatter to format a date, otherwise use 'mm/dd/yy'.
function defaultDateFormatter(date, preferredFormatter) {
if (!preferredFormatter)
preferredFormatter = "mm/dd/yy";
if (typeof preferredFormatter == 'string')
return $.datepicker.formatDate(preferredFormatter, date);
else
return preferredFormatter(date);
}
// Functions for Parsing & Formatting on the Model & View
function parseDateFromModel(date) {
return defaultDateParse(date, dateHandler.model.parse)
}
function parseDateFromView(date) {
return defaultDateParse(date, dateHandler.view.parse)
}
function formatDateForModel(date) {
return defaultDateFormatter(date, dateHandler.model.format)
}
function formatDateForView(date) {
return defaultDateFormatter(date, dateHandler.view.format)
}
var defaultDateViewFormat = (
typeof dateHandler.view.format == 'string'
? dateHandler.view.format
: 'mm/dd/yy'
)
// Initialize the jQuery-ui datePicker
var datePickerSettings = $.extend({ dateFormat: defaultDateViewFormat }, $scope.$eval(attrs.uiDatePicker))
var oldOnSelect = datePickerSettings.onSelect;
datePickerSettings.onSelect = function (dateVal) {
$scope.$apply(function () {
element.focus().val(dateVal);
updateModel();
})
if (oldOnSelect)
oldOnSelect.apply(this, arguments)
}
element.datepicker(datePickerSettings);
if (ngModel) {
// Specify how UI should be updated
ngModel.$render = function () {
element.val(ngModel.$viewValue || '');
};
// Listen for change events to enable binding
element.bind('blur keyup change', function () {
$scope.$apply(updateModel);
});
// Write data to the model
function updateModel() {
ngModel.$setViewValue(element.val());
}
// Convert the model into a string value
ngModel.$formatters.push(function (v) {
if (v != "" && v != null)
return formatDateForView(parseDateFromModel(v));
return null;
});
// Convert the string value into the model
ngModel.$parsers.push(function (v) {
if (v != "" && v != null)
return formatDateForModel(parseDateFromView(v))
return null;
});
}
}
};
})
Similar to praveepd (using their's as a base), but this will include deep model selection.
http://jsfiddle.net/c8PMa/
var myApp = angular.module('myApp', ['myApp.directives']);
function MainCtrl($scope) {
$scope.deepValue = {
fromDate: null,
toDate: null
}
}
angular.module('myApp.directives', [])
.directive('myDatepicker', function() {
return function(scope, element, attrs) {
element.datepicker({
changeYear : true,
changeMonth : true,
appendText : '(yyyy-mm-dd)',
dateFormat : 'yy-mm-dd',
onSelect: function(dateText) {
var mdlAttr = $(this).attr('ng-model').split(".");
if (mdlAttr.length > 1) {
var objAttr = mdlAttr[mdlAttr.length-1];
var s = scope[mdlAttr[0]];
for (var i=0; i < mdlAttr.length-2; i++) {
s = s[mdlAttr[i]];
}
s[objAttr] = dateText;
} else {
scope[mdlAttr[0]] = dateText;
}
scope.$apply();
}
});
}
});​
http://jsfiddle.net/9BRNf/74/ here is the solution :)
code:
var myApp = angular.module('myApp', ['myApp.directives']);
function MainCtrl() {
}
angular.module('myApp.directives', [])
.directive('myDatepicker', function() {
return {
require: '?ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
element.datepicker({
changeYear : true,
changeMonth : true,
appendText : '(yyyy-mm-dd)',
dateFormat : 'yy-mm-dd',
onSelect: function(date) {
ngModelCtrl.$setViewValue(date);
scope.$apply();
}
});
}
}
});
Old question, but this was the first hit for me in google search for this. Anyways, I used dual datepickers working together using jquery and angular directives, so I thought I'd share to help anyone else trying to do this.
Here's the plunker for it:
http://plnkr.co/edit/veEmtCM3ZnQAhGTn5EGy?p=preview
Basically it initializes the form using json. The datepickers have their own conditions like mindate's, etc. The first select box if true = disables sundays on the calendars, else enables them.
The viewmodel get's updates when 'done' is clicked. Here's a bit of the code for one of the datepickers:
Html:
<input id="StartDate" data-ng-model="viewModel.startdate" date-from />
Directive:
app.directive('dateFrom', function() {
return function (scope, element, attrs) {
var doDate = $('#EndDate');
element.datepicker({
dateFormat: 'dd-M-yy', showOtherMonths: true,
selectOtherMonths: true, minDate: '0',
beforeShowDay: function (date) {
var day = date.getDay();
console.log(scope.nosunday);
if (scope.nosunday === 'true') return [(day !== 0), '']; // disable sundays
else return [true, ''];
},
onSelect: function (selectedDate) {
var toDate = new Date(element.datepicker("getDate"));
toDate.setDate(toDate.getDate() + 1);
doDate.datepicker('option', 'minDate', toDate);
scope.viewModel.startdate = selectedDate;
scope.viewModel.enddate = doDate.val();
}
});
}
})
Feel free to optimize it further. Post a comment with a forked plunk if you do :)
I had just trimmed the code, have a look at this: http://jsfiddle.net/YU5mV/
HTML
<input id="date1" value="1/1/1980" ng-model="fromDate" my-datepicker />
<input id="date2" value="1/1/1980" ng-model="toDate" my-datepicker />
JavaScript
angular.module('myApp.directives', [])
.directive('myDatepicker', function() {
return function(scope, element, attrs) {
element.datepicker({
changeYear : true,
changeMonth : true,
appendText : '(yyyy-mm-dd)',
dateFormat : 'yy-mm-dd',
onSelect: function(dateText) {
var mdlAttr = $(this).attr('ng-model');
scope[mdlAttr] = dateText;
scope.$apply();
}
});
}
});

jQuery UI autocomplete (combobox): how to fill it with the result of an AJAX request?

Is it possible to work with combobox as with usual jquery-ui ajax autocomplete field?
What I need?
I want there will be some default options and when user try to put any letters it must connect to the server to find requested information (as usual remote json autocomplete).
Is it possible at all?
Here's a heavily modified version of the jQueryUI example (gist):
$.widget("ui.combobox", {
_create: function() {
var _self = this
, options = $.extend({}, this.options, {
minLength: 0,
source: function(request, response) {
if (!request.term.length) {
response(_self.options.initialValues);
} else {
if (typeof _self.options.source === "function") {
_self.options.source(request, response);
} else if (typeof _self.options.source === "string") {
$.ajax({
url: _self.options.source,
data: request,
dataType: "json",
success: function(data, status) {
response(data);
},
error: function() {
response([]);
}
});
}
}
}
});
this.element.autocomplete(options);
this.button = $("<button type='button'> </button>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.insertAfter(this.element)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("ui-corner-right ui-button-icon")
.click(function() {
if (_self.element.autocomplete("widget").is(":visible")) {
_self.element.autocomplete("close");
return;
}
_self.element.autocomplete("search", "");
_self.element.focus();
});
}
});
Usage:
$("input_element_selector").combobox({
initialValues: ['array', 'of', 'values'],
source: /* <-- function or string performing remote search */,
/* any other valid autocomplete options */
});
Example: http://jsfiddle.net/Jpqa8/
The widget uses the supplied initialValues array as the source when the length of the search is "0" (this happens when the user clicks the dropdown button).
Supply a source parameter (function or string) that performs the remote search. You can also use any other options you would usually use with the autocomplete widget.

How do I pass an extra parameter to Jquery Autocomplete field?

I'm using the JQuery Autocomplete in one of my forms.
The basic form selects products from my database. This works great, but I'd like to further develop so that only products shipped from a certain zipcode are returned. I've got the backend script figured out. I just need to work out the best way to pass the zipcode to this script.
This is how my form looks.
<form>
<select id="zipcode">
<option value="2000">2000</option>
<option value="3000">3000</option>
<option value="4000">4000</option>
</select>
<input type="text" id="product"/>
<input type="submit"/>
</form>
And here is the JQuery code:
$("#product").autocomplete
({
source:"product_auto_complete.php?postcode=" + $('#zipcode').val() +"&",
minLength: 2,
select: function(event, ui){
//action
}
});
This code works to an extent. But only returns the first zipcode value regardless of which value is actually selected. I guess what's happening is that the source URL is primed on page load rather than when the select menu is changed. Is there a way around this? Or is there a better way overall to achieve the result I'm after?
You need to use a different approach for the source call, like this:
$("#product").autocomplete({
source: function(request, response) {
$.getJSON("product_auto_complete.php", { postcode: $('#zipcode').val() },
response);
},
minLength: 2,
select: function(event, ui){
//action
}
});
This format lets you pass whatever the value is when it's run, as opposed to when it's bound.
This is not to complicated men:
$(document).ready(function() {
src = 'http://domain.com/index.php';
// Load the cities straight from the server, passing the country as an extra param
$("#city_id").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term,
country_id : $("#country_id").val()
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
delay: 300
});
});
jQuery("#whatJob").autocomplete(ajaxURL,{
width: 260,
matchContains: true,
selectFirst: false,
minChars: 2,
extraParams: { //to pass extra parameter in ajax file.
"auto_dealer": "yes",
},
});
I believe you are correct in thinking your call to $("#product").autocomplete is firing on page load. Perhaps you can assign an onchange() handler to the select menu:
$("#zipcode").change(resetAutocomplete);
and have it invalidate the #product autocomplete() call and create a new one.
function resetAutocomplete() {
$("#product").autocomplete("destroy");
$("#product").autocomplete({
source:"product_auto_complete.php?postcode=" + $('#zipcode').val(),
minLength: 2,
select: function(event, ui){... }
});
}
You may want your resetAutocomplete() call to be a little smarter -- like checking if the zip code actually differs from the last value -- to save a few server calls.
This work for me. Override the event search:
jQuery('#Distribuidor_provincia_nombre').autocomplete({
'minLength':0,
'search':function(event,ui){
var newUrl="/conf/general/provincias?pais="+$("#Distribuidor_pais_id").val();
$(this).autocomplete("option","source",newUrl)
},
'source':[]
});
Hope this one will help someone:
$("#txt_venuename").autocomplete({
source: function(request, response) {
$.getJSON('<?php echo base_url(); ?>admin/venue/venues_autocomplete',
{
user_id: <?php echo $user_param_id; ?>,
term: request.term
},
response);
},
minLength: 3,
select: function (a, b) {
var selected_venue_id = b.item.v_id;
var selected_venue_name = b.item.label;
$("#h_venueid").val(selected_venue_id);
console.log(selected_venue_id);
}
});
The default 'term' will be replaced by the new parameters list, so you will require to add again.
$('#product').setOptions({
extraParams: {
extra_parameter_name_to_send: function(){
return $("#source_of_extra_parameter_name").val();
}
}
})
$('#txtCropname').autocomplete('Handler/CropSearch.ashx', {
extraParams: {
test: 'new'
}
});

Resources