Ajax / Jquery Autocomplete with JSON data does not show background style - javascript

I want to render Ajax / Jquery Autocomplete in my Spring App but unable to show background style I get result as shown
my Autocomplete code is
<script type="text/javascript">$(document).ready(function() {
//attach autocomplete
$("#tagQuery").autocomplete({
minLength: 1,
delay: 500,
//define callback to format results
source: function (request, response) {
$.getJSON("/getTags", request, function(result) {
response($.map(result, function(item) {
return {
// following property gets displayed in drop down
label: item.tagTitle,
// following property gets entered in the textbox
value: item.tagTitle,
// following property is added for our own use
tag_url: "http://" + window.location.host + "/" + item.tagId + "/" + item.tagTitle
}
}));
});
},
//define select handler
select : function(event, ui) {
if (ui.item) {
event.preventDefault();
$("#selected_tags span").append(''+ ui.item.label +'');
//$("#tagQuery").value = $("#tagQuery").defaultValue
var defValue = $("#tagQuery").prop('defaultValue');
$("#tagQuery").val(defValue);
$("#tagQuery").blur();
return false;
}
}
});
});
UPDATE
Adding line
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
solved issue of ui it now looks good
but when I select any value it is not placed in input text and how can I add comma separated multiple results in input box.
please any help is a day saving...

Related

Autocomplete: how to get automatically value on focus if no values selected

From the comment in this question, I've seen how to set an autocomplete field to empty if no element from the list has been selected.
What I am trying to implement is that when a user does not select any element from the autocomplete list and switches to the next field, one of the following should happen:
If there was at least on element displayed in the autocomplete list, take automatically the first element of that list. In the screenshot below, Mannheim should be automatically selected if the user goes to another field without selecting any element.
If no element was displayed, make the field empty again.
If tried the suggestions from here and here, but without success.
This is my code:
var cities = //function that provides a list of cities depending on the input string (edited to clarify)
$('.autocomplete-city').autocomplete({
source: function (request, response) {
response($.map(cities( request.term ), function (value, key) {
return {
label: value.label,
value: value.value
}
}));
},
// manage what happens if user does not click any option from autocomplete
change: function(event, ui){
if (ui.item == null){
if ( list_from_autocomplete == null ){ // I tried here several possibilities but none seem to work
$(this).val('');
$(this).focus();
} else {
$(this).val( first_item_in_list ); // Despite the existing questions, I could not make it work...
}
}
},
minLength: 2,
autoFocus: true,
});
How could this be done?
You could search all the cities that contains the user input and if you get only one result, put it in the autocomplete.
1) So, in the change event you could check if user selected an item:
change: function(event, ui){
if(ui.item){
//user select an item
}
else{
//here let's try to set the autocomplete
}
2) Search the cities that contains the user's input:
var result = cities.filter(function( obj ) {
return obj.label.indexOf(searched);
});
3) Finally, if you get just one result, set the autocomplete with that value:
if(result.length==1){
$(this).val(result[0].label);
}
Please see following snippet:
var cities = [
{"label":"Alessandria","id":"AL"},
{"label":"Milano","id":"MI"},
{"label":"Pisa","id":"PI"},
{"label":"Pistoia","id":"PT"}
];
$(".autocomplete-city").autocomplete({
source: cities,
select: function(event, ui){
if(ui.item){
console.log('select', ui.item.label);
return ui.item.label;
}
else{
console.log('select with null value');
}
},
change: function(event, ui){
var searched = this.value;
console.log("Searched: " + searched);
if(ui.item){
console.log('change', ui.item.id);
}
else{
console.log('change with null value');
var result = cities.filter(function( obj ) {
return obj.label.toLowerCase().indexOf(searched.toLowerCase()) !== -1;
});
if(result.length>0){
$(this).val(result[0].label);
}
else{
//clear the autocomplete
$(this).val("");
}
}
}
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<input class="autocomplete-city"/>
In the above example there are following cities: Alessandria, Milano, Pisa, Pistoia.
If you digit in textbox "Mil" or "Ale" and just press the tab, the autocomplete will be filled with the single result starting with "Mil" or "Ale".
Instead, when you digit "Pis" the autocomplete will be cleared.
I hope it was clear, bye.
Updated:
In order to get the first result when user leaves the autocomplete without selecting any city, you could check result.length>0 and set the first value from result in to the autocomplete:
var result = cities.filter(function( obj ) {
return obj.label.toLowerCase().indexOf(searched.toLowerCase()) !== -1;
});
if(result.length>0){
$(this).val(result[0].label);
}
else{
//clear the autocomplete
$(this).val("");
}

Materialize CSS on chip delete

I have been trying to get the tag of a deleted chip from the div in the Materialize chips class, but nothing is working.
Here is what I have already tried.
$('.chips').on('chip.delete', function(e, chip){
console.log(chip);
console.log(e);
console.log(chip.tag);
});
None of the above is working.
With just only console.log(chip), I get undefined error in JavaScript console, but the function is firing when I delete the chip. I am just not able to get the value of tag of deleted chip. I want to store the tag in a variable.
I am creating chips dynamically on Materialize date select:
$('#pm_date').change(function () {
var chipvalue = $(this).val();
if (chipvalue !== "") {
// checking if tag already exits
if ($("#date_chip_select:contains(" + chipvalue + ")").length > 0) {
alert('Date already selected');
} else {
var appendstring = "<div class='chip' id='date_chip_child_" + chip_id + "'>" + chipvalue + "<i class='material-icons close'>close</i></div>";
}
}
});
Here is the fiddle: https://jsfiddle.net/hq22mne4/1/
chips.js, which is part of materialize, doesn't seem to expose any methods for adding or removing chips programmatically. It seems to exclusively listen for an enter keydown event and then internally add the chip.
So, I stitched together a workaround that does just that. I set potential chip's value within your onchange event:
$("#datechips").find('input').val($(this).val());
And create the chip when date picker is closed:
$('.datepicker').pickadate({
selectMonths: true,
selectYears: 15,
onClose: function() {
// add chip via filling the input and simulating enter
$("#datechips").find('input').trigger({ type : 'keydown', which : 13 });
},
});
It may not be ideal, but you should be able to tailor this going forward.
https://jsfiddle.net/j3ej8240/
I've also had a lot of trouble working this out. This is how I capture the add and delete chip events without using jQuery:
function chipDeleted(e, data) {
console.log("Chip was deleted with text: " + data.childNodes[0].textContent);
}
function chipAdded(e, data) {
console.log("Chip was added with text: " + data.childNodes[0].textContent);
}
//
document.addEventListener("DOMContentLoaded", function (e) {
console.log("DOM fully loaded and parsed");
var firstTag = "Initial Tag";
var elems = document.querySelectorAll('.chips');
var instances = M.Chips.init(elems, {
data:[{
tag: firstTag
}],
autocompleteOptions: {
limit: Infinity,
minLength: 1
},
placeholder: "No search...",
onChipDelete: function (e, data) { chipDeleted(e, data) },
onChipAdd: function (e, data) { chipAdded(e, data) }
});
});
And my HTML part is like this:
<body>
<div class="chips search-history"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
</body>

Jquery autosuggest

I am new to jquery.
I am using the below code for showing autosuggest in text box.
$().ready(function() {
function formatItem(row) {
return row[0] + " (<strong>id: " + row[1] + "</strong>)";
}
function formatResult(row) {
return row[0].replace(/(<.+?>)/gi, '');
}
//$("#suggest1").autocomplete(cities);
$("#custName").autocomplete(arrNames, {
multiple: false,
minChars: 0,
width: 190,
matchContains: true,
autoFill: false,
mustMatch: true,
max: 20,
}
});
});
My problem is I want to call a javascript function along with the index of arrNames as parameter when user select one name from autosuggest. Please help me.
Here is how you do it (using jQuery ui autocomplete) :
$("#custName").autocomplete(
source: arrNames,
select: function (event, ui) {
//Do stuff here
}
}
From jqueryUI website :
Select
Triggered when an item is selected from the menu; ui.item refers to
the selected item. The default action of select is to replace the text
field's value with the value of the selected item. Canceling this
event prevents the value from being updated, but does not prevent the
menu from closing.
EDIT :
It seems you are using Autocomplete plugin from http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
This plugin is deprecated... You should use jQuery ui autocomplete : http://jqueryui.com/demos/autocomplete/

jQuery UI autocomplete with item and id

I have the following script which works with a 1 dimensional array. Is it possible to get this to work with a 2 dimensional array? Then whichever item is selected, by clicking on a second button on the page, should display the id of whichever item is selected.
This is the script with the 1 dimensional array:
var $local_source = ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"];
$("#txtAllowSearch").autocomplete({
source: $local_source
});
This is the script for the button to check the id, which is incomplete:
$('#button').click(function() {
// alert($("#txtAllowSearch").someone_get_id_of_selected_item);
});
You need to use the ui.item.label (the text) and ui.item.value (the id) properties
$('#selector').autocomplete({
source: url,
select: function (event, ui) {
$("#txtAllowSearch").val(ui.item.label); // display the selected text
$("#txtAllowSearchID").val(ui.item.value); // save selected id to hidden input
}
});
$('#button').click(function() {
alert($("#txtAllowSearchID").val()); // get the id from the hidden input
});
[Edit] You also asked how to create the multi-dimensional array...
You should be able create the array like so:
var $local_source = [[0,"c++"], [1,"java"], [2,"php"], [3,"coldfusion"],
[4,"javascript"], [5,"asp"], [6,"ruby"]];
Read more about how to work with multi-dimensional arrays here: http://www.javascriptkit.com/javatutors/literal-notation2.shtml
From the Overview tab of jQuery autocomplete plugin:
The local data can be a simple Array
of Strings, or it contains Objects for
each item in the array, with either a
label or value property or both. The
label property is displayed in the
suggestion menu. The value will be
inserted into the input element after
the user selected something from the
menu. If just one property is
specified, it will be used for both,
eg. if you provide only
value-properties, the value will also
be used as the label.
So your "two-dimensional" array could look like:
var $local_source = [{
value: 1,
label: "c++"
}, {
value: 2,
label: "java"
}, {
value: 3,
label: "php"
}, {
value: 4,
label: "coldfusion"
}, {
value: 5,
label: "javascript"
}, {
value: 6,
label: "asp"
}, {
value: 7,
label: "ruby"
}];
You can access the label and value properties inside focus and select event through the ui argument using ui.item.label and ui.item.value.
Edit
Seems like you have to "cancel" the focus and select events so that it does not place the id numbers inside the text boxes. While doing so you can copy the value in a hidden variable instead. Here is an example.
My code only worked when I added 'return false' to the select function. Without this, the input was set with the right value inside the select function and then it was set to the id value after the select function was over. The return false solved this problem.
$('#sistema_select').autocomplete({
minLength: 3,
source: <?php echo $lista_sistemas;?> ,
select: function (event, ui) {
$('#sistema_select').val(ui.item.label); // display the selected text
$('#sistema_select_id').val(ui.item.value); // save selected id to hidden input
return false;
},
change: function( event, ui ) {
$( "#sistema_select_id" ).val( ui.item? ui.item.value : 0 );
}
});
In addition, I added a function to the change event because, if the user writes something in the input or erases a part of the item label after one item was selected, I need to update the hidden field so that I don´t get the wrong (outdated) id. For example, if my source is:
var $local_source = [
{value: 1, label: "c++"},
{value: 2, label: "java"}]
and the user type ja and select the 'java' option with the autocomplete, I store the value 2 in the hidden field. If the user erase a letter from 'java', por exemple ending up with 'jva' in the input field, I can´t pass to my code the id 2, because the user changed the value. In this case I set the id to 0.
Just want to share what worked on my end, in case it would be able to help someone else too. Alternatively based on Paty Lustosa's answer above, please allow me to add another approach derived from this site where he used an ajax approach for the source method
http://salman-w.blogspot.ca/2013/12/jquery-ui-autocomplete-examples.html#example-3
The kicker is the resulting "string" or json format from your php script (listing.php below) that derives the result set to be shown in the autocomplete field should follow something like this:
{"list":[
{"value": 1, "label": "abc"},
{"value": 2, "label": "def"},
{"value": 3, "label": "ghi"}
]}
Then on the source portion of the autocomplete method:
source: function(request, response) {
$.getJSON("listing.php", {
term: request.term
}, function(data) {
var array = data.error ? [] : $.map(data.list, function(m) {
return {
label: m.label,
value: m.value
};
});
response(array);
});
},
select: function (event, ui) {
$("#autocomplete_field").val(ui.item.label); // display the selected text
$("#field_id").val(ui.item.value); // save selected id to hidden input
return false;
}
Hope this helps... all the best!
Assuming the objects in your source array have an id property...
var $local_source = [
{ id: 1, value: "c++" },
{ id: 2, value: "java" },
{ id: 3, value: "php" },
{ id: 4, value: "coldfusion" },
{ id: 5, value: "javascript" },
{ id: 6, value: "asp" },
{ id: 7, value: "ruby" }];
Getting hold of the current instance and inspecting its selectedItem property will allow you to retrieve the properties of the currently selceted item. In this case alerting the id of the selected item.
$('#button').click(function() {
alert($("#txtAllowSearch").autocomplete("instance").selectedItem.id;
});
<script type="text/javascript">
$(function () {
$("#MyTextBox").autocomplete({
source: "MyDataFactory.ashx",
minLength: 2,
select: function (event, ui) {
$('#MyIdTextBox').val(ui.item.id);
return ui.item.label;
}
});
});
The above responses helped but, did not work in my implementation.
The instead of using setting the value using jQuery, I am returning the value from the function to the select option.
The MyDataFactory.ashx page has a class with three properties Id, Label, Value.
Pass the List into the JavaScript serializer, and return the response.
I do not think that there is need to hack around the value and label properties, use hidden input fields or to suppress events. You may add your own custom property to each Autocomplete object and then read that property value later.
Here is an example.
$(#yourInputTextBox).autocomplete({
source: function(request, response) {
// Do something with request.term (what was keyed in by the user).
// It could be an AJAX call or some search from local data.
// To keep this part short, I will do some search from local data.
// Let's assume we get some results immediately, where
// results is an array containing objects with some id and name.
var results = yourSearchClass.search(request.term);
// Populate the array that will be passed to the response callback.
var autocompleteObjects = [];
for (var i = 0; i < results.length; i++) {
var object = {
// Used by jQuery Autocomplete to show
// autocomplete suggestions as well as
// the text in yourInputTextBox upon selection.
// Assign them to a value that you want the user to see.
value: results[i].name;
label: results[i].name;
// Put our own custom id here.
// If you want to, you can even put the result object.
id: results[i].id;
};
autocompleteObjects.push(object);
}
// Invoke the response callback.
response(autocompleteObjects);
},
select: function(event, ui) {
// Retrieve your id here and do something with it.
console.log(ui.item.id);
}
});
The documentation mentions you have to pass in an array of objects with label and value properties. However, you may certainly pass in objects with more than these two properties and read them later.
Here is the relevant part I am referring to.
Array: An array can be used for local data. There are two supported
formats: An array of strings: [ "Choice1", "Choice2" ] An array of
objects with label and value properties: [ { label: "Choice1", value:
"value1" }, ... ] The label property is displayed in the suggestion
menu. The value will be inserted into the input element when a user
selects an item. If just one property is specified, it will be used
for both, e.g., if you provide only value properties, the value will
also be used as the label.
At last i did it Thanks alot friends, and a special thanks to Mr https://stackoverflow.com/users/87015/salman-a because of his code i was able to solve it properly. finally my code is looking like this as i am using groovy grails i hope this will help somebody there.. Thanks alot
html code looks like this in my gsp page
<input id="populate-dropdown" name="nameofClient" type="text">
<input id="wilhaveid" name="idofclient" type="text">
script Function is like this in my gsp page
<script>
$( "#populate-dropdown").on('input', function() {
$.ajax({
url:'autoCOmp',
data: {inputField: $("#populate-dropdown").val()},
success: function(resp){
$('#populate-dropdown').autocomplete({
source:resp,
select: function (event, ui) {
$("#populate-dropdown").val(ui.item.label);
$("#wilhaveid").val(ui.item.value);
return false;
}
})
}
});
});
</script>
And my controller code is like this
def autoCOmp(){
println(params)
def c = Client.createCriteria()
def results = c.list {
like("nameOfClient", params.inputField+"%")
}
def itemList = []
results.each{
itemList << [value:it.id,label:it.nameOfClient]
}
println(itemList)
render itemList as JSON
}
One more thing i have not set id field hidden because at first i was checking that i am getting the exact id , you can keep it hidden just put type=hidden instead of text for second input item in html
Thanks !
I've tried above code displaying (value or ID) in text-box insted of Label text. After that I've tried event.preventDefault() it's working perfectly...
var e = [{"label":"PHP","value":"1"},{"label":"Java","value":"2"}]
$(".jquery-autocomplete").autocomplete({
source: e,select: function( event, ui ) {
event.preventDefault();
$('.jquery-autocomplete').val(ui.item.label);
console.log(ui.item.label);
console.log(ui.item.value);
}
});
This can be done without the use of hidden field. You have to take benefit of the JQuerys ability to make custom attributes on run time.
('#selector').autocomplete({
source: url,
select: function (event, ui) {
$("#txtAllowSearch").val(ui.item.label); // display the selected text
$("#txtAllowSearch").attr('item_id',ui.item.value); // save selected id to hidden input
}
});
$('#button').click(function() {
alert($("#txtAllowSearch").attr('item_id')); // get the id from the hidden input
});
Auto Complete Text box binding using Jquery
## HTML Code For Text Box and For Handling UserID use Hidden value ##
<div class="ui-widget">
#Html.TextBox("userName")
#Html.Hidden("userId")
</div>
Below Library's is Required
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
Jquery Script
$("#userName").autocomplete(
{
source: function (request,responce)
{
debugger
var Name = $("#userName").val();
$.ajax({
url: "/Dashboard/UserNames",
method: "POST",
contentType: "application/json",
data: JSON.stringify({
Name: Name
}),
dataType: 'json',
success: function (data) {
debugger
responce(data);
},
error: function (err) {
alert(err);
}
});
},
select: function (event, ui) {
$("#userName").val(ui.item.label); // display the selected text
$("#userId").val(ui.item.value); // save selected id to hidden input
return false;
}
})
Return data Should be below format
label = u.person_full_name,
value = u.user_id

Force a user to select from JQuery UI Autocomplete and populate a hidden field after selecting

I have a large HTML form that contains many fields that need an autocomplete for accounts. I tag these fields with the class AccountLookup and jQuery does the dirty work for the autocomplete:
$(".AccountLookup").autocomplete({
source: function (request, response) {
$.ajax({
url: "Lookup.asmx/GetAccounts",
data: "{ 'Search': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.Value
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 3
});
Now, when a user selects something from the autocomplete I need it to populate a hidden field just BEFORE the tagged input field; probably using something like:
$(this).prev().val(item.Key);
How do I incorporate this functionality? Also, how do I force a user to select from the auto complete? (All the values are pre-defined, the user cannot add new ones.)
EDIT:
As far as I understand from inspecting the DOM, the select option is currently filling in the hidden form field.
select: function (event, ui) {
$(this).prev().val(ui.item.key);
}
I know this is an old post--- but I ran into it in trying to solve a similar problem (forcing the user to select an item from the list)...
$("#ac").autocomplete({
source: function (req, resp) {
//add code here...
},
select: function (e, ui) {
$(this).next().val(ui.item.id);
},
change: function (ev, ui) {
if (!ui.item)
$(this).val("");
}
});
$(".AccountLookup").autocomplete({
/*...*/
}).result(function(event, item) {
$(this).prev().val(item.Key);
});
You could also use a jQuery validate to ensure that the field is populated.
for force selection, you can use "change" event of Autocomplete
var availableTags = [
"ActionScript",
"AppleScript"
];
$("#tags").autocomplete({
source: availableTags,
change: function (event, ui) {
if(!ui.item){
//http://api.jqueryui.com/autocomplete/#event-change -
// The item selected from the menu, if any. Otherwise the property is null
//so clear the item for force selection
$("#tags").val("");
}
}
});
For the selection action, try using the formatItem option. You can format each result to have an onclick event that will populate the other textbox.
For the forcing to select from autocomplete, you need to use the mustMatch option.
http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions
I ran into this same problem quite awhile ago and some post helped me along with it. I have since modified the code as I found that there were cases I wanted one or more fields to fill in from the information returned. In the select option of the autocomplete I added a function.
select: function (e, ui) {ReSetField({'txtID':'id','txtPrice':'price' [,etc...]}, ui) }
The function "ResetFields" then takes in a JSON list of element names paired with fieldnames and uses the fieldnames to match the elements in the ui object. The value can then be pulled from the ui item and put into the html element.
function ReSetField(_flds, _vals) {
//Set up the flds to be reset with values passed in.
try {
if (_flds != undefined) {
if ($.type(_flds) == 'string') {
_flds = JSON.parse(_flds);
};
var _fld = null;
var _val = '';
$.each(_flds, function (index) {
if (index.length > 0) {
_fld = '#' + index; //Set the forms field name to set
_val = _flds[index]; //Pick up the field name to set the fields value
$fld = $(_fld);
$fld.val(_vals.item[_val]); //Set the fields value to the returned value
}
}
})
};
}
catch (e) {
alert('Cannot set field ' + _fld + '.');
}
}
By sticking the "fieldlist" into the HTML element as an attribute like "fieldlist" and using a class like "comboBox" I can then use a single function to find all ComboBox elements and set up the autocomplete on a form reducing the amount of code required to handle 2 or more lookups on a form.

Categories