How to use array in autocomplete textbox jquery? - javascript

For Example
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
var availableTags = [ "ActionScript", "AppleScript", "Asp"];
var availableTagsCode = ["1", "2", "3"];
$( "#tags" ).autocomplete({ source: availableTags });
});
</script>
<input id="tags" name="name">
<input id="tags_code" name="code">
Actually, I have tried to change code while select suggestion using following code:
$("#tags_code").val(availableTagsCode);
I need to select suggestion test if i will select 0th array from tag the 0th code should assign to name="code" textbox.
Please help me to resolve this problem.

Set select event handler
$(function() {
var availableTags = ["ActionScript", "AppleScript", "Asp"];
var availableTagsCode = ["1", "2", "3"];
$("#tags").autocomplete({
source: availableTags,
select: function(e, ui) {
$('#tags_code').val(availableTagsCode[availableTags.indexOf(ui.item.value)]);
}
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<input id="tags" name="name">
<input id="tags_code" name="code">

You can define a select event handler:
$( "#tags" ).autocomplete({
source: availableTags,
select: function(event, ui) {
var index = availableTags.indexOf(ui.item.value);
$("#tags_code").val(availableTagsCode[index]);
}
});
Here is the working JSFiddle demo.
Actually, jQuery UI allows you to use an array of objects with value and label properties when you provide source.
So, something like this will work and look better:
var tags = [
{"label": "ActionScript", "value": 1},
{"label": "AppleScript", "value": 2},
{"label": "Asp", "value": 3}
];
$( "#tags" ).autocomplete({
source: tags,
select: function (event, ui) {
$("#tags_code").val(ui.item.value);
}
});
JSFiddle demo for the second approach.
If you don't want the value to be replaced after choosing, you can use custom property instead of value:
var tags = [
{"label": "ActionScript", "code": 1},
{"label": "AppleScript", "code": 2},
{"label": "Asp", "code": 3}
];
$( "#tags" ).autocomplete({
source: tags,
select: function (event, ui) {
$("#tags_code").val(ui.item.code);
}
});
JSFiddle demo.

<script type="text/javascript">
$(document).ready(function () {
$("#textBoxID").autocomplete({
source: function (request, responce) {
$.ajax({
url: "webservice_Name.asmx/webservice_functionName",
method: "post",
contentType: "application/json;charset=utf-8",
data: JSON.stringify({ parameterName: request.term }),
dataType: 'json',
success: function (data) {
responce(data.d);
if (data.d.length > 0)
$('#spnError').text("");
else
$('#spnError').text("Not Matching Any Result");
console.log(data.d.length);
},
error: function (err) {
alert(err);
}
});
},
minLength: 2,
select: function (event, ui) {
console.log("You selected: " + ui.item.label);
$.ajax({
url: "webservice_Name.asmx/webservice_functionNameForgetID",
method: "post",
contentType: "application/json;charset=utf-8",
data: JSON.stringify({ parameterName: ui.item.label }),
dataType: 'json',
success: function (data) {
console.log(data.d);
},
error: function (err) {
alert(err);
}
});
}
});
});
</script>

Related

Autocomplete form field with JQuery from external JSON not working

The first step of my complex form is to autocomplete a field with some external data located in a json. I tried and followed multiple examples and documentation but I am unable to make it work...
For this external json:
[
{
"Nombre": "Adoración Pérez",
"DNI": "23123",
"Telefono": ""
},
{
"Nombre": "Adriana Suárez",
"DNI": "345345435",
"Telefono": ""
},
{
"Nombre": "Agueda Delmiro",
"DNI": "6u56u6tJ",
"Telefono": 12312434
},
{
"Nombre": "Aida Aguilera",
"DNI": "46456456A",
"Telefono": 13123213
},
{
"Nombre": "Aladino Valdés",
"DNI": "67867845eG",
"Telefono": ""
},
{
"Nombre": "Alberto Martinez",
"DNI": "235436456",
"Telefono": ""
}
]
This is my full JS:
$(function() {
var entries = []
$.getJSON('pacientes.json', function(json) {
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
entries.push(item);
}
}
console.log(entries)
$("#species").autocomplete({
minLength: 0,
source: entries,
focus: function(event, ui) {
$("#species").val(ui.item.Nombre);
return false;
},
select: function(event, ui) {
$("#species").val(ui.item.Nombre);
$( "#identifiant" ).val( ui.item.DNI );
return false;
}
})
});
});
This is my full HTML:
<!DOCTYPE html>
<html>
<body>
<h2>HTML Forms</h2>
<form action="/action_page.php">
<label for="species">Species: </label>
<input id="species">
<label for="identifiant">Identifiant: </label>
<input id="identifiant" style="width: 6em;">
</form>
<p>If you click the "Submit" button, the form-data will be sent to a page called "/action_page.php".</p>
<script src="js/jquery-3.5.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="js/parse_data.js"></script>
</body>
</html>
I tried several different options but cannot autocomplete data. Thank you very much!
Consider the following example.
$(function() {
// Load entries once
var entries = [];
$.getJSON('pacientes.json', function(json) {
$.each(function(key, val) {
if (json.hasOwnProperty(key)) {
entries.push(json);
}
});
// Initialize Autocomplete
$("#species").autocomplete({
minLength: 0,
source: function(req, resp) {
var myData = [];
$.each(entries, function(key, val) {
if (val.Nombre.indexOf(req.term) == 0) {
myData.push({
label: val.Nombre,
value: val.DNI,
Nombre: val.Nombre,
DNI: val.DNI,
Telefono: val.Telefono
});
}
console.log(myData);
resp(myData);
});
},
focus: function(event, ui) {
$("#species").val(ui.item.Nombre);
return false;
},
select: function(event, ui) {
$("#species").val(ui.item.Nombre);
$("#identifiant").val(ui.item.DNI);
return false;
}
});
});
});
<h2>HTML Forms</h2>
<form action="/action_page.php">
<label for="species">Species: </label>
<input id="species" type="text" />
<label for="identifiant">Identifiant: </label>
<input id="identifiant" type="text" style="width: 6em;" />
</form>
<p>If you click the "Submit" button, the form-data will be sent to a page called "/action_page.php".</p>
<script src="js/jquery-3.5.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="js/parse_data.js"></script>
This will allow you to configure custom data and still format the Array as needed.
Reference: https://api.jqueryui.com/autocomplete/#option-source
You can also make use of $.ui.autocomplete.filter().
var myData = [];
$.each(entries, function(key, val) {
myData.push({
label: val.Nombre,
value: val.DNI,
Nombre: val.Nombre,
DNI: val.DNI,
Telefono: val.Telefono
});
console.log(myData);
resp($.ui.autocomplete.filter(myData, req.term));
});

Cannot pass autocomplete selection value to input field

I'm trying to add the value of my autocomplete selection to a specific input field with id initialNameField.
Autocomplete:
<div class="ui-widget">
<label for="tags">Search: </label>
<input class="tags" />
</div>
Input:
<input type="text" th:field="*{selectedInitialName}" class="initialNameField" id="initialNameField"
name="initialName"/>
Includes:
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
Autocomplete Script:
<script type="text/javascript">
//<![CDATA[
$(function() {
var availableTags = [
"1",
"2",
"3",
"4",
];
$(".tags").autocomplete({
source: availableTags,
minLength: 1,
dataType: 'json',
select: function(event, ui) {
$('#initialNameField').val(ui.item.id);
}
});
});
//]]>
</script>
What should I be doing to make this work?
You have to set the value like this:
$('#initialNameField').val(ui.item.value); // Or ui.item.label
Because ui is a object like: {"item":{"label":"1","value":"1"}}
Working fiddle here: https://jsfiddle.net/wc0rtpa9/
Try to use ui.item.label when you setting selected text to textbox.
$(document).ready(function () {
var availableTags = [
"1",
"2",
"3",
"4",
];
$(".tags").autocomplete({
source: availableTags,
minLength: 1,
dataType: 'json',
select: function(event, ui) {
$('#initialNameField').val(ui.item.label); // input the selected text
}
});
});
Here is the sample working code : http://jsfiddle.net/32Bck/625/

Not able to select the values of jQuery Autocomplete?

I am trying and experimenting to create a customized jQuery UI Autocomplete but I am failing in the first step itself. When I click on the values that populate there is no response. I am not able to select the values of autocomplete. Can anyone please let me know why?
Below is my code:
HTML:
<!DOCTYPE html>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>
<title>test</title>
<body>
<div>Select:</div>
<input id="project" style="width:380px;">
</body>
Javascript:
(function($){
var $project = $('#project');
var projects = [
{
value: "test1",
label: "test1",
desc: "test1",
icon: "jquery_32x32.png"
},
{
value: "test2",
label: "test2",
desc: "test2",
icon: "jqueryui_32x32.png"
}
];
$project.autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$project.val(ui.item.value);
return false;
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
var inner_html = '<table><tr><td>' + item.value + '</td></tr></table>';
return $("<li></li>")
.data("item.autocomplete", item)
.append(inner_html)
.appendTo(ul);
};
})(jQuery);
You just need to replace:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>
with:
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
Check following fiddle:
(function($){
var $project = $('#project');
var projects = [
{
value: "test1",
label: "test1",
desc: "test1",
icon: "jquery_32x32.png"
},
{
value: "test2",
label: "test2",
desc: "test2",
icon: "jqueryui_32x32.png"
}
];
$project.autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$project.val(ui.item.value);
return false;
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
var inner_html = '<table><tr><td>' + item.value + '</td></tr></table>';
return $("<li></li>")
.data("item.autocomplete", item)
.append(inner_html)
.appendTo(ul);
};
})(jQuery);
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<title>test</title>
</head>
<body>
<div>Select:</div>
<input id="project" style="width:380px;">
</body>

Why are JQuery autocomplete results not showing in browser?

I have a working fiddle, but the autocomplete does not display anything in the browser. The fiddle can be seen here: Working Fiddle
In the HTML, I have one input element for testing purposes:
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type ="text/javascript" src="myScripts.js"></script>
<script type ="text/javascript" src="jquery.csv-0.71.js"></script>
<script type ="text/javascript" src="csvToArray.v2.1.js"></script>
</head>
<body>
<div data-role="page" id="main">
<div data-role="header">
<h1>Test</h1>
</div>
<div id="contentDiv" data-role="content">
<input type="text" id="food" placeholder="Type (First Name) Here" />
</div>
</div>
</body>
In my javascript, I am initializing a json variable by reading text from a file. I have tested that my initialization is successful by displaying an alert of my json variable. I am trying to use that json variable as the source in my autocomplete. Below, I have simplified my javascript by hard coding the initialization of the json variable in order to narrow down the problem:
var jsonVersion =
[{"description":"mac and cheese", "servingSize":"1 cup", "calories":"500"},
{"description":"slice of pizza", "servingSize":"1 slice", "calories":"400"},
{"description":"oreo cookie", "servingSize":"1 cookie", "calories":"100"},
{"description":"salad", "servingSize":"1 cup", "calories":"50"},
{"description":"apple", "servingSize":"1 apple", "calories":"70"}];
$('#food').autocomplete({
source: jsonVersion,
select: function (event, ui) {
selectedObj = ui.item;
alert("selected object=" + selectedObj.value);
},
minLength: 1
});
Any idea why this would work in the fiddle but not in the browser? I am not getting any browser errors. Simply nothing is being displayed when I type in the textbox.
EDIT
Perhaps it is in the way I am populating my jsonVersion - although when I print the jsonVersion via "alert", it looks right. Any advice on what I am doing wrong here would be appreciated. Here is the entire javascript file. "data" is an array of arrays and I am looping through each of those arrays to create an object, in turn creating an array of Objects. Then I convert the array of objects to json using stringify:
$(function ($) {
var jsonVersion;
var arrayOfObjects;
$.ajax({
type: "GET",
url: "test.js",
dataType: "text",
success: function(data) {
data = $.csv.toArrays(data);
arrayOfObjects = new Array();
for(var i=1; i<data.length; i++)//skipping over header
{
var foodObject = new Object();
foodObject.label = data[i][1];
foodObject.weight = data[i][2];
foodObject.servingSize = data[i][3];
foodObject.calories = data[i][4];
arrayOfObjects.push(foodObject);
}
jsonVersion = JSON.stringify(arrayOfObjects);
alert(jsonVersion);
}
});
$('#food').autocomplete({
source: jsonVersion,
select: function (event, ui) {
selectedObj = ui.item;
alert("selected object=" + selectedObj.value);
},
minLength: 1
});
})
You have two major problems:
You're passing a string to the source option of autocomplete. When you do this, the widget attempts to use that string as a URL to retrieve results from. Since this string is a JSON representation of the array you built as the result of the AJAX call, this is obviously not going to work the way you expect it to. You should simply use arrayOfObjects instead.
You're initializing the autocomplete widget outside of the success callback for your AJAX request. This means that the autocomplete widget is initialized with an empty source. You can fix by simply moving the initialization into the success callback.
Fixing both of these things should fix your issues:
$(function ($) {
$.ajax({
type: "GET",
url: "test.js",
dataType: "text",
success: function(data) {
data = $.csv.toArrays(data);
var arrayOfObjects = [];
for(var i=1; i<data.length; i++)//skipping over header
{
var foodObject = new Object();
foodObject.label = data[i][1];
foodObject.weight = data[i][2];
foodObject.servingSize = data[i][3];
foodObject.calories = data[i][4];
arrayOfObjects.push(foodObject);
}
$('#food').autocomplete({
source: arrayOfObjects,
select: function (event, ui) {
selectedObj = ui.item;
alert("selected object=" + selectedObj.value);
},
minLength: 1
});
}
});
});
Looks like your script is not inside dom ready handler.
In jsfiddle, in the second dropdown in the left side panel onload tells the app to add a wrapping onload handler for the script - if you select on head it will not work fiddle
jQuery(function ($) {
var jsonObject = [{
"label": "mac and cheese",
"servingSize": "1 cup",
"calories": "500"
}, {
"label": "slice of pizza",
"servingSize": "1 slice",
"calories": "400"
}, {
"label": "oreo cookie",
"servingSize": "1 cookie",
"calories": "100"
}, {
"label": "salad",
"servingSize": "1 cup",
"calories": "50"
}, {
"label": "apple",
"servingSize": "1 apple",
"calories": "70"
}];
$('#food').autocomplete({
source: jsonObject,
select: function (event, ui) {
selectedObj = ui.item;
alert("selected object=" + selectedObj.value);
},
minLength: 1
});
})
Demo: Fiddle
Update:
$(function ($) {
var arrayOfObjects = [];
$.ajax({
type: "GET",
url: "test.js",
dataType: "text",
success: function (data) {
data = $.csv.toArrays(data);
for (var i = 1; i < data.length; i++) //skipping over header
{
var foodObject = new Object();
foodObject.label = data[i][1];
foodObject.weight = data[i][2];
foodObject.servingSize = data[i][3];
foodObject.calories = data[i][4];
arrayOfObjects.push(foodObject);
}
}
});
$('#food').autocomplete({
source: arrayOfObjects,
select: function (event, ui) {
selectedObj = ui.item;
alert("selected object=" + selectedObj.value);
},
minLength: 1
});
})

jQuery Autocomplete > Select > Link

I have this code implemented and I like how straight forward it is because I plan to add ALOT to the Source -- however for the life of me I cannot figure out how to add the selected one as a Link.
EG > Begin Typing > Autofill works > Select > Go to that URL
Current Code:
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$("input#autocomplete").autocomplete({
source: ["NYC", "LA", "Philly", "Chitown", "DC", "SF", "Peru"]
});
});
</script>
</head>
<body style="font-size:62.5%;">
<input id="autocomplete" />
</body>
</html>
I found a few discussions about this on here, but none of the code suggestions had worked. How do I add a URL associated with the values above; I'd love if I could keep the same syntax and near the values just add; EG: "peru" www.peru.com
You could add a url property to each object in the source array and then set window.location to that URL when the user selects an item:
$(document).ready(function() {
$("input#autocomplete").autocomplete({
source: [
{ value: "NYC", url: 'http://www.nyc.com' },
{ value: "LA", url: 'http://www.la.com' },
{ value: "Philly", url: 'http://www.philly.com' },
{ value: "Chitown", url: 'http://www.chitown.com' },
{ value: "DC", url: 'http://www.washingtondc.com' },
{ value: "SF", url: 'http://www.sanfran.com' },
{ value: "Peru", url: 'http://www.peru.com' }
],
select: function (event, ui) {
window.location = ui.item.url;
}
});
});

Categories