JQuery Autocomplete - Force choice - javascript

I have a form working with JQuery Autocomplete and it works fairly well. Now I need another element to force a user to select a valid choice in the autocomplete input. The can type whatever they want and everything is filtered by autocomplete. But they have to select something from the served list.
If they don't the inputfield must get blanked. Tried out a few things with change and select to no avail. This is the code of my autocomplete. I saw some examples operation with data instead of source. This seems to make a big difference
$(function () {
$("#sp_name").autocomplete({
minLength: 2,
delay: 300,
source: function (request, response) {
$.ajax({
url: "./Search/",
dataType: "json",
data: {
term: request.term,
zoekterm: $("#al").html()
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.naam,
value: item.naam
}
}));
}
});
}
})
});

Try this:
I am using a local list here, but you can achieve this via json data source too.
Just add a change event. The only problem this can have is that if user does not click on
the suggestion, it will turn blank (even if user is entering the same text as suggestion).
It will be mandatory for user to click on the suggestion.
var list = ["c", "c++", "c#","Basic","Mongo"];
$('#auto').autocomplete({
source: list,
select: function (event, ui) {
$(this).val(ui.item ? ui.item : " ");},
change: function (event, ui) {
if (!ui.item) {
this.value = '';}
//else { Return your label here }
}
});
JsFidle for it: http://jsfiddle.net/sarcastic/7KdZP/112/
In your case, Change function would be something like this:
change: function (event, ui)
{
if (!ui.label) { this.value = ''; }
}

Related

AutoComplete with Key-Value in grid, showing key when focus

I am using paramquery grid component in which I am trying to use autocomplete.
Column Model for branch:
{ title: "Branch", dataIndx: "branchId", width: 150,
filter: { type: "select",
condition: 'equal',
prepend: { '': '--All--' },
listeners: ['change'],
valueIndx: "branchId",
labelIndx: "branchName",
options: branchList,
},
editor: {
type: "textbox",
init: autoCompleteEditor
//type: function (ui) { return dropdowneditor(this, ui); }
},
render: function (ui) {
for (var i = 0; i < branchList.length; i++) {
var option = branchList[i];
if (option.branchId == ui.rowData.branchId) {
return option.branchName;
}
}
}
}
autoCompleteEditorMethod:
var autoCompleteEditor = function (ui) {
var $inp = ui.$cell.find("input");
//initialize the editor
$inp.autocomplete({
source: function(request, response) {
var rows = imAutocompleteJSONParse(branchList);// this method converting my JSON object into Value and label format.
return response(rows);
},
selectItem: { on: true }, //custom option
highlightText: { on: true }, //custom option
minLength: 0,
select: function(event, ui) {
event.preventDefault();
$(this).val(ui.item.label);
},
focus: function(event, ui) {
event.preventDefault();
$("#search").val(ui.item.label);
}
}).focus(function () {
//open the autocomplete upon focus
$(this).autocomplete("search", "");
});
}
I get branch id into my grid and I have branchList JSON which have branch id & branch Name. Inside grid my render function showing branchName on UI.
But when I click on searchable dropdown I'm getting branch id.
Below snapshot may explain my issue properly.
Summary of issue: I am getting branch id in Grid. With help of render method I am able to show branch name on grid. but when I click on textbox I getting branch id.
http://jsfiddle.net/v4zx8tjc/4/
Like blackmiaool suggests in his comment, this question would be easier to answer with a live demo using something like JSFiddle.
Based on what I can see in your question, which isn't that much, there are a few areas I would take a second look at.
The Source function in JQuery.autoComplete. Where is branchList coming from? I don't see it declared anywhere and why are you not using the 'request' param?
Not sure what your custom properties are doing but it might be a good idea to verify those are not interfering with the results.
Edit 1: Looking back at the code you posted I think I see where your branchList variable is coming from. It would be very helpful to see your imAutocompleteJSONParse() method because I believe that may be where things are breaking down.

Clear all of the list items of Select2 rather than the selected

I have a cascade Select2 ddl and when I select the master ddl, I populate the Detail ddl without no problem. On the other hand, when I select another item on master and then click the detail, at the first time the detail ddl lists the previous items just a miliseconds. So, I need to clear all of the list items besides the selected item when the main ddl's selected index changed. Is it possible? I have tried to all of the solution methods below, but they only clear the selected item. Any idea?
$('#ProjectId').select2('data', null);
$('#ProjectId').select2('data', { id: null, text: null })
$('#ProjectId').empty();
$('#ProjectId').val(null).trigger("change");
$("#ProjectId").remove();
$('#ProjectId').val('').trigger('change');
#Html.DropDownListFor(m => m.ProjectId, Enumerable.Empty<SelectListItem>(), "Select")
$(document).ready(function () {
var issueType = $("#ProjectId");
issueType.select2({
allowClear: true,
ajax: {
url: '/Controller/GetProjects',
dataType: 'json',
delay: 250,
data: function (params) {
return {
query: params.term, //search term
page: params.page,
id: selectedMasterId
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
newData.push({
id: item.Id,
text: item.Description
});
});
return { results: newData };
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
});
});
$('#MasterId').change(function () {
selectedMasterId = $(this).val();
$('#ProjectId').select2('val', '');
$('#ProjectId').select2('data', null);
}
});
$('#id').empty().trigger("change");
Where '#id' is the jQuery selector for your select2 element.
On the select element put onchange="removeOthers(this)" in js code write this function:
function removeOthers(that){
$('option', that).not(':eq(0), :selected').remove();
//now refresh your select2
}

meteor handle form input

I'm using meteor to build a web app that shows stock information. I currently have a input on the client side which takes in text. The input is hooked up to a Lookup API by Markit on Demand. This is the code:
Template.LookupTemplate.onRendered(function() {
this.$("#Lookup")
.focus()
.autocomplete({
source: function(request,response) {
$.ajax({
url: "http://dev.markitondemand.com/api/v2/Lookup/jsonp",
dataType: "jsonp",
data: {
input: request.term
},
success: function(data) {
response( $.map(data, function(item) {
return {
label: item.Name + " (" +item.Exchange+ ")",
value: item.Symbol
}
}));
},
minLength: 0,
select: function(event,ui ) {
console.log(ui.item);
}
});
}
});
}); //Closing tag of LoookupTemplate.onRendered
How do I capture the selection by the client? When the user starts typing a company name, the jquery autocomplete kicks in and gives the client a list of options to select from. Once the user selects it and hits "enter" (submits it), the page reloads to
http://localhost:3000/Overview?stockname=AAPL
How do I capture that input (AAPL in this case) and then pass it to another function that builds a chart for that particular stock?
--Router.js
Router.configure({
// This is the default layout/top-level template
layoutTemplate: 'layout'
});
Router.map(function() {
this.route('/', {
path: '/',
action: function() {
this.redirect('landingpage')
document.title = 'Cash'
}
});
// Route for the landing page when user is not logged in
this.route('landingpage', {
path: '/landingpage',
after: function() {
document.title = 'Cash'
}
});
// Route to our main app. Note that I use / path as I treat this as default behavior
this.route('/Overview', {
path: '/Overview',
after: function () {
document.title = 'Cash';
}
});
})
IronRouter only can read the param when you define them in the router. For the case of dynamically param created by the API, the best way is using javascript to read it. Please have a look at the solution in here

How to trigger another ajax request when autocomplete selection is made?

I am trying to use autocomplete which call a method on the server to populate the list.
Corresponding JS file calls
$(function () {
$("#search").autocomplete(
{
source: "requests/search",
minLength: 2,
select: function (event, ui) {
//Here I would like to send the parameters.
var itemid = ui.item.id;
alert(itemid);
// How to call another ajax method.
}
})
});
Call its search method inside select event. Try this.
$(function () {
$("#search").autocomplete(
{
source: "requests/search",
minLength: 2,
select: function (event, ui) {
$(this).autocomplete( "search" , ui.item.value );
}
})
});

Trigger autocomplete using button/emulate combobox functionality

I'm using jqGrid in a project, and have managed to replace some of the controls on the edit/input modal with a jQuery autocomplete control, but would prefer something like a combobox.
How would it be possible to replicate the functionality, as I'm struggling to get any of the jQuery combobox add-ons working.
My data set is in json format, so it would be cool if I can keep it that way.
I think the jQuery plugin you're looking for is Flexselect which implements the Liquid metal search ranking algorithm to create the desired affect.
This is what I did to turn my autocompletes into comboboxes.
initImpactEdit = function (elem) {
setTimeout(function () {
$(elem).autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("ImpactOptions")',
dataType: "json",
data: {
filter: request.term
},
success: function (data) {
response($.map(eval(data), function (item) {
return {
label: item.Impact_name,
value: item.Impact_name,
DTI_ID: item.DTI_ID
}
})
);
}
})
}
}
});
$(elem).addClass('customAutoCompleteWidth');
$('<button class="customDropdown"> </button>')
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.insertAfter(elem)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("ui-corner-right ui-button-icon")
.click(function () {
var widg = $(elem);
if (widg.autocomplete("widget").is(":visible")) {
widg.autocomplete("close");
return;
}
if (widg.val().length == 0) {
// pass empty string as value to search for, displaying all results
widg.autocomplete("search", "*");
} else { widg.autocomplete("search", widg.val()); }
widg.focus();
});
}, 100);
};
{ name: 'Impact', index: 'Impact', editoptions: { dataInit: initImpactEdit } },

Categories