I am implementing jQuery UI Autocomplete and am wondering if there is any way to only allow a selection from the suggested results that are returned as opposed to allowing any value to be input into the text box.
I am using this for a tagging system much like the one used on this site, so I only want to allow users to select tags from a pre-populated list returned to the autocomplete plugin.
You could also use this:
change: function(event,ui){
$(this).val((ui.item ? ui.item.id : ""));
}
The only drawback I've seen to this is that even if the user enters the full value of an acceptable item, when they move focus from the textfield it will delete the value and they'll have to do it again. The only way they'd be able to enter a value is by selecting it from the list.
Don't know if that matters to you or not.
I got the same problem with selected not being defined. Got a work-around for it and added the toLowerCase function, just to be safe.
$('#' + specificInput).autocomplete({
create: function () {
$(this).data('ui-autocomplete')._renderItem = function (ul, item) {
$(ul).addClass('for_' + specificInput); //usefull for multiple autocomplete fields
return $('<li data-id = "' + item.id + '">' + item.value + '</li>').appendTo(ul);
};
},
change:
function( event, ui ){
var selfInput = $(this); //stores the input field
if ( !ui.item ) {
var writtenItem = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val().toLowerCase()) + "$", "i"), valid = false;
$('ul.for_' + specificInput).children("li").each(function() {
if($(this).text().toLowerCase().match(writtenItem)) {
this.selected = valid = true;
selfInput.val($(this).text()); // shows the item's name from the autocomplete
selfInput.next('span').text('(Existing)');
selfInput.data('id', $(this).data('id'));
return false;
}
});
if (!valid) {
selfInput.next('span').text('(New)');
selfInput.data('id', -1);
}
}
}
http://jsfiddle.net/pxfunc/j3AN7/
var validOptions = ["Bold", "Normal", "Default", "100", "200"]
previousValue = "";
$('#ac').autocomplete({
autoFocus: true,
source: validOptions
}).keyup(function() {
var isValid = false;
for (i in validOptions) {
if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
isValid = true;
}
}
if (!isValid) {
this.value = previousValue
} else {
previousValue = this.value;
}
});
This is how I did it with a list of settlements:
$("#settlement").autocomplete({
source:settlements,
change: function( event, ui ) {
val = $(this).val();
exists = $.inArray(val,settlements);
if (exists<0) {
$(this).val("");
return false;
}
}
});
i just modify to code in my case & it's working
selectFirst: true,
change: function (event, ui) {
if (ui.item == null){
//here is null if entered value is not match in suggestion list
$(this).val((ui.item ? ui.item.id : ""));
}
}
you can try
Ajax submission and handling
This will be of use to some of you out there:
$('#INPUT_ID').autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: autocompleteURL,
data: "{'data':'" + $('INPUT_ID').val() + "'}",
dataType: 'json',
success: function (data) {
response(data.d);
},
error: function (data) {
console.log('No match.')
}
});
},
change: function (event, ui) {
var opt = $(this).val();
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: autocompleteURL,
data: "{'empName':'" + name + "'}",
dataType: 'json',
success: function (data) {
if (data.d.length == 0) {
$('#INPUT_ID').val('');
alert('Option must be selected from the list.');
} else if (data.d[0] != opt) {
$('#INPUT_ID').val('');
alert('Option must be selected from the list.');
}
},
error: function (data) {
$(this).val('');
console.log('Error retrieving options.');
}
});
}
});
I'm on drupal 7.38 and
to only allow input from select-box in autocomplete
you only need to delete the user-input at the point,
where js does not need it any more - which is the case,
as soon as the search-results arrive in the suggestion-popup
right there you can savely set:
**this.input.value = ''**
see below in the extract from autocomplete.js ...
So I copied the whole Drupal.jsAC.prototype.found object
into my custom module and added it to the desired form
with
$form['#attached']['js'][] = array(
'type' => 'file',
'data' => 'sites/all/modules/<modulname>_autocomplete.js',
);
And here's the extract from drupal's original misc/autocomplete.js
modified by that single line...
Drupal.jsAC.prototype.found = function (matches) {
// If no value in the textfield, do not show the popup.
if (!this.input.value.length) {
return false;
}
// === just added one single line below ===
this.input.value = '';
// Prepare matches.
=cut. . . . . .
If you would like to restrict the user to picking a recommendation from the autocomplete list, try defining the close function like this. The close function is called when the results drop down closes, if the user selected from the list, then event.currentTarget is defined, if not, then the results drop down closed without the user selecting an option. If they do not select an option, then I reset the input to blank.
//
// Extend Autocomplete
//
$.widget( "ui.autocomplete", $.ui.autocomplete, {
options: {
close: function( event, ui ) {
if (typeof event.currentTarget == 'undefined') {
$(this).val("");
}
}
}
});
You can actually use the response event in combination to the change event to store the suggested items like so:
response: function (event, ui) {
var list = ui.content.map(o => o.value.toLowerCase());
},
change: function (event, ui) {
if (!ui.item && list.indexOf($(this).val().toLowerCase()) === -1 ) { $(this).val('');
}
Related
I have implemented autocomplete feature using JQuery, but now I wanted to store last 20 searched per inputfield in browser. So, if user when focuses the suggestion will be fetched from the browser. If user types then from Rest API using ajax I am fetching the data.
$("input[type='text']").autocomplete({
source: function(request, response) {
var id = $(this.element).prop("id");
var id2=this.element[0].id;
var id3=$(this.element.get(0)).attr('id');
console.log(id);
console.log(id2);
console.log(id3);
var params = {'page':1,'size':"10"};
params[id]=request.term;
var jsonParams = JSON.stringify(params);
$.ajax({
type: "POST",
url:"http://localhost:5645/search",
data: jsonParams,
headers: {"X-CSRF-TOKEN": $("input[name='_csrf']").val()},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//const result = new Set()
var result=[];
console.log(id);
console.log(msg.details)
console.log(msg.details.length)
for(var i = 0; i < msg.details.length; i++) {
var obj = msg.details[i];
if(obj!=null && columnMapping[id]!=undefined && obj[columnMapping[id]]!=undefined){
console.log(obj[columnMapping[id]]);
//result.add(obj[columnMapping[id]]);
result.push(obj[columnMapping[id]]);
}
console.log(result);
}
//response(Array.from(result));
response(result);
}
/* error: function() {
response([]);
} */
})
},
select: function(event, ui) {
alert(ui.item ? ("You picked '" + ui.item.label) : "Nothing selected, input was " + this.value);
return false;
}
}).autocomplete("instance")._renderItem = function(ul, item) {
console.log('test');
var item = $("<div>" + item.label + "</div>")
return $("<li>").append(item).appendTo(ul);
};
Above is the jquery code which I am using for autocomplete. So, if no input is there I need to fetch from browser recent search. So, when user types unique search keys should be inserted. How I can store and retrive using javascript.
I have to search inside a json file with a value from my input, everything is fine capturing the value and the event, but when I iterate something unexpected happens for me.
How can I select an object based on this search?.
the problem is that when doing .each it goes through all the records, even those not found.
$( document ).on('turbolinks:load', common_events)
function common_events(){
$('.rut-input').on('change', function(event){
$rut = $(this).val();
var searchField = $rut;
var expression = new RegExp(searchField, "i");
event.preventDefault();
$.ajax({
type: "GET",
url: '/companies/',
dataType: 'JSON',
success: function(companies){
$.each(companies, function(i, company) {
if (company.rut.search(expression) > -1){
console.log(company.id);
$('.name-input').empty();
$('.name-input').val(company.name);
$('.name-input').addClass('disabled-input');
$('.form-group').removeClass('hide');
console.log(company.address);
if (company.address == null ){
$('.address-input').removeClass('disabled-input');
};
}
else {
console.log('no encuentra');
console.log(company);
$('.form-group').removeClass('hide');
$('.form-control').removeClass('disabled-input');
};
});
},
error: function(companies){
console.log('A ocurrido un error')
},
});
});
}
when executing the event, both the if and else are executed at the same time.
Seems like you don't really want to iterate the companies array with each. You want to find a matching company, and then do something with that record.
success: function(companies){
const company = companies.find(c => c.rut.search(expression) > -1);
if (company) {
console.log(company.id);
$('.name-input').empty();
$('.name-input').val(company.name);
$('.name-input').addClass('disabled-input');
$('.form-group').removeClass('hide');
console.log(company.address);
if (company.address == null ){
$('.address-input').removeClass('disabled-input');
}
} else {
console.log('no encuentra');
console.log(company);
$('.form-group').removeClass('hide');
$('.form-control').removeClass('disabled-input');
}
},
Hello everyone I have a table that's dynamically generated from database.
This is the table.
I have all the code that works fine,but I only need proper timing of execution
1) Check if all mandatory fields are populated on button click, if not don't send ajax.
2) When all mandatory fields are populated on button click then call ajax and send proper values to c# and later to database.
First I need to check if all mandatory fields are filled in(check Mandatory column(yes or no values):
$(function () {
$("#myButton").on("click", function () {
// Loop all span elements with target class
$(".IDMandatory").each(function (i, el) {
// Skip spans which text is actually a number
if (!isNaN($(el).text())) {
return;
}
// Get the value
var val = $(el).text().toUpperCase();
var isRequired = (val === "TRUE") ? true :
(val === "FALSE") ? false : undefined;
// Mark the textbox with required attribute
if (isRequired) {
// Find the form element
var target = $(el).parents("tr").find("input,select");
if (target.val()) {
return;
}
// Mark it with required attribute
target.prop("required", true);
// Just some styling
target.css("border", "1px solid red");
}
});
})
});
If not don't call ajax and send values. If all fields are populated then call ajax to send values to c#.
This is the ajax code that takes values from filed and table and send's it to c# WebMethod and later to database.
$(function () {
$('#myButton').on('click', function () {
var ddl = $('#MainContent_ddlBusinessCenter').val()
var myCollection = [];
$('#MainContent_gvKarakteristike tbody').find('tr:gt(0)').each(function (i, e) {
var row = $(e);
myCollection.push({
label: valuefromType(row.find(row.find('td:eq(1)').children())),
opis: valuefromType(row.find(row.find('td:eq(3)').children()))
});
});
console.log(myCollection);
function valuefromType(control) {
var type = $(control).prop('nodeName').toLowerCase();
switch (type) {
case "input":
return $(control).val();
case "span":
return $(control).text();
case "select":
('Selected text:' + $('option:selected', control).text());
return $('option:selected', control).text();
}
}
var lvl = $('#MainContent_txtProductConstruction').val()
if (lvl.length > 0) {
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({ 'omyCollection': myCollection, 'lvl': lvl, 'ddl': ddl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (parseInt(response.d) > 0)
alert("Saved successfully.");
else
alert("This object already exists in the database!");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
}
else {
alert("Please fill in the Product Construction field!")
}
});
});
I need code to execute first mandatory fields and when they are all filled in then call ajax part of the code!
Can anyone please help !
If you need more explanation just ask !
Thanks in advance !
Update Liam helped allot me but ajax is not working on button click.
function validate() {
// Loop all span elements with target class
$(".IDMandatory").each(function (i, el) {
// Skip spans which text is actually a number
if (!isNaN($(el).text())) {
return;
}
// Get the value
var val = $(el).text().toUpperCase();
var isRequired = (val === "TRUE") ? true :
(val === "FALSE") ? false : undefined;
// Mark the textbox with required attribute
if (isRequired) {
// Find the form element
var target = $(el).parents("tr").find("input,select");
if (target.val()) {
return;
}
// Mark it with required attribute
target.prop("required", true);
// Just some styling
target.css("border", "1px solid red");
}
});
}
function sendAjax() {
var ddl = $('#MainContent_ddlBusinessCenter').val()
var myCollection = [];
$('#MainContent_gvKarakteristike tbody').find('tr:gt(0)').each(function (i, e) {
var row = $(e);
myCollection.push({
label: valuefromType(row.find(row.find('td:eq(1)').children())),
opis: valuefromType(row.find(row.find('td:eq(3)').children()))
});
});
console.log(myCollection);
function valuefromType(control) {
var type = $(control).prop('nodeName').toLowerCase();
switch (type) {
case "input":
return $(control).val();
case "span":
return $(control).text();
case "select":
('Selected text:' + $('option:selected', control).text());
return $('option:selected', control).text();
}
}
var lvl = $('#MainContent_txtProductConstruction').val()
if (lvl.length > 0) {
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({ 'omyCollection': myCollection, 'lvl': lvl, 'ddl': ddl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (parseInt(response.d) > 0)
alert("Saved successfully.");
else
alert("This object already exists in the database!");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
}
else {
alert("Please fill in the Product Construction field!")
}
}
$(function () {
$('#myButton').on('click', function () {
if (validate()){
sendAjax();
}
})
});
If you want to execute these in order why don't you just add one click handler that calls each function:
function validate(){
// Loop all span elements with target class
$(".IDMandatory").each(function (i, el) {
// Skip spans which text is actually a number
....etc.
}
function sendAjax(){
var ddl = $('#MainContent_ddlBusinessCenter').val()
var myCollection = [];
..etc.
}
$(function () {
$('#myButton').on('click', function () {
validate();
sendAjax();
}
});
Seems it would make sense if your validate function actually returns true or false if your form was valid too. then you could:
$(function () {
$('#myButton').on('click', function () {
if (validate()){
sendAjax();
}
}
});
I'm not really sure why your doing this:
// Mark it with required attribute
target.prop("required", true);
when you validate? If you just add this into your HTML it will handle required. adding it here seems a bit strange. I'm guessing your not actually submitting the form? It'd make more sense to add the validation message yourself rather than use this attribute.
Your codes not working because your not returning anything from your validate function. It's not 100% clear to me what is valid and what isn't so I can't alter this. But you need to add return true; for valid cases and return false;for invalid cases for the if statement if (validate()){ to work.
This is what I have:
searchTimeoutID;
InitQuickSearch = function() {
$( 'input#quick-search' ).autocomplete({
source: []
});
$('input#quick-search', document).on('keyup', function(e) {
switch(e.which) {
default: // live search
window.clearTimeout(searchTimeoutID); // remove timer
var str = $(this).val(); // search string
if (str !== '') { // do the search
searchTimeoutID = window.setTimeout(LiveSearch, 100);
}
break;
}
});
};
LiveSearch = function() {
var str = $('input#quick-search').val();
if(str !== '') {
$.ajax({
type: 'POST',
url: '/livesearch',
data: { query: str },
cache: false,
success: function(data){
var results = data.split(',');
alert(results); // displays correct results here
$( 'input#quick-search' ).autocomplete( 'option', { source: results });
},
error: function(response) {
printError(response);
}
});
}
return false;
};
When I output the results variable using alert(results), the values look correct.
However, when I try and update the values in autocomplete it does not display the correct values. Also, I have to press the down key for the menu to appear.
$( 'input#quick-search' ).autocomplete( 'option', { source: results });
What am I doing wrong?
I just had to change:
searchTimeoutID = window.setTimeout(LiveSearch, 100);
to:
LiveSearch();
I have created jQuery UI autocomplete which is working very good. But my requirement is that what I display as list should also select same in text box. But it is not selecting
For example list like XXX (XYZ) but when I select it only select XXX not XXX (XYZ)
what I am missing !!
function getDeptStations() {
$("#txDestination").autocomplete({
source: function (request, response) {
var term = request.term;
var Query = "";
if (lang === "en")
Query = "City_Name_EN";
else if (lang === "fr")
Query = "City_Name_FR";
if (lang === "de")
Query = "City_Name_DE";
if (lang === "ar")
Query = "City_Name_AR";
var requestUri = "/_api/lists/getbytitle('Stations')/items?$select=City_Code," + Query + "&$filter=startswith(" + Query + ",'" + term + "')";
$.ajax({
url: requestUri,
type: "GET",
async: false,
headers: {
"ACCEPT": "application/json;odata=verbose"
}
}).done(function (data) {
if (data.d.results) {
response($.map(eval(data.d.results), function (item) {
return {
label: item[Query] + " (" + item.City_Code + ")",
value: item[Query],
id: item[Query]
}
}));
}
else {
}
});
},
response: function (event, ui) {
if (!ui.content.length) {
var noResult = { value: "", label: "No cities matching your request" };
ui.content.push(noResult);
}
},
select: function (event, ui) {
$("#txDestination").val(ui.item.label);
cityID = ui.item.id;
},
minLength: 1
});
}
Almost there, just return a false from select event.
select: function (event, ui) {
$("#txDestination").val(ui.item.label);
cityID = ui.item.id;
return false;
},
or Simply
select: function (event, ui) {
alert(ui.item.id);
return false;
},
This will guide jquery autocomplete to know that select has set a value.
Update: This is not in the documentation, I figured out by digging into source code, took me some time. But indeed it deserves to be in the doc or in options.
in this case you have to options
the obvious one set value:item[Query] + " (" + item.City_Code + ")" but I am assuming this is not the option.
Handle the selection by yourself first check the api doc and you will see event like below. with event.target you can access your input with ui you can access you selected item.
$( ".selector" ).autocomplete({
select: function( event, ui ) {}
});
I understand its been answered already. but I hope this will help someone in future and saves so much time and pain.
After getting the results in autocomplete you can use below code for keeping the value in the autocomplete textbox field. (you can replace 'CRM.$' with '$' or 'jQuery' depending on your jQuery version)
select: function (event, ui) {
var label = ui.item.label;
var value = ui.item.value;
//assigning the value to hidden field for saving the id
CRM.$( 'input[name=product_select_id]' ).val(value);
//keeping the selected label in the autocomplete field
CRM.$('input[id^=custom_78]').val(label);
return false;
},
complete code is below: This one I did for a textbox to make it Autocomplete in CiviCRM. Hope it helps someone
CRM.$( 'input[id^=custom_78]' ).autocomplete({
autoFill: true,
select: function (event, ui) {
var label = ui.item.label;
var value = ui.item.value;
// Update subject field to add book year and book product
var book_year_value = CRM.$('select[id^=custom_77] option:selected').text().replace('Book Year ','');
//book_year_value.replace('Book Year ','');
var subject_value = book_year_value + '/' + ui.item.label;
CRM.$('#subject').val(subject_value);
CRM.$( 'input[name=product_select_id]' ).val(ui.item.value);
CRM.$('input[id^=custom_78]').val(ui.item.label);
return false;
},
source: function(request, response) {
CRM.$.ajax({
url: productUrl,
data: {
'subCategory' : cj('select[id^=custom_77]').val(),
's': request.term,
},
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
},
success: function(result){
result = jQuery.parseJSON( result);
//console.log(result);
response(CRM.$.map(result, function (val,key) {
//console.log(key);
//console.log(val);
return {
label: val,
value: key
};
}));
}
})
.done(function( data ) {
if ( console && console.log ) {
// console.log( "Sample of dataas:", data.slice( 0, 100 ) );
}
});
}
});
PHP code on how I'm returning data to this jquery ajax call in autocomplete:
/**
* This class contains all product related functions that are called using AJAX (jQuery)
*/
class CRM_Civicrmactivitiesproductlink_Page_AJAX {
static function getProductList() {
$name = CRM_Utils_Array::value( 's', $_GET );
$name = CRM_Utils_Type::escape( $name, 'String' );
$limit = '10';
$strSearch = "description LIKE '%$name%'";
$subCategory = CRM_Utils_Array::value( 'subCategory', $_GET );
$subCategory = CRM_Utils_Type::escape( $subCategory, 'String' );
if (!empty($subCategory))
{
$strSearch .= " AND sub_category = ".$subCategory;
}
$query = "SELECT id , description as data FROM abc_books WHERE $strSearch";
$resultArray = array();
$dao = CRM_Core_DAO::executeQuery( $query );
while ( $dao->fetch( ) ) {
$resultArray[$dao->id] = $dao->data;//creating the array to send id as key and data as value
}
echo json_encode($resultArray);
CRM_Utils_System::civiExit();
}
}