how can I use a value of an autocomplete inputfield in a second-inputfield?
I wrote this script below but I dont know how to use the variables from the first in the second-inputfield? the first-field responses:
[{"label":"TEST","value":1}]
and i need the "value" for the second field..
$(document).ready(function(){
jQuery('#first-field').autocomplete({
source:'',
minLength: 2,
delay:0,
select: function(event, ui) {
event.preventDefault();
$("first-field").val(ui.item.label);
},
focus: function(event, ui) {
event.preventDefault();
$("#first-field").val(ui.item.label);
}
});
jQuery('#second-field').autocomplete({
source:'',
minLength: 2,
delay:0,
select: function(event, ui) {
event.preventDefault();
$("second-field").val(ui.item.label);
},
focus: function(event, ui) {
event.preventDefault();
$("#second-field").val(ui.item.label);
}
});
});
Try This
<label for="FirstField">First Name</label> <input id="FirstField" />
<br />
<br />
<label for="SecondField">Second Name</label> <input id="SecondField" />
$(function() {
$('#FirstField, #SecondField').autocomplete({
source: [
"Some Name",
"Value",
"Place"
],
minLength: 0,
select: function( event, ui ) {
$('#SecondField').val(ui.item.value);
$('#FirstField').val(ui.item.value);
return false;
}
})
.focus(function()
{
var self = this;
window.setTimeout(function()
{
if (self.value.length == 0)
$(self).autocomplete('search', '');
});
})
$('#FirstField').change(function() {
$('#SecondField').val($(this).val());
});
});
Related
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));
});
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/
If you enter "che" in https://jsfiddle.net/mgjftrdz/ (code from http://jqueryui.com/autocomplete/#multiple) it lists two items:
Cheese
Cream-cheese
What changes to that would I need to make those particular characters bold in the drop-down results like this?
Cheese
Cream-cheese
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#tags")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).autocomplete("instance").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function(request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
availableTags, extractLast(request.term)));
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
});
You can try
$(function() {
var availableTags = [{
label: 'honey',
value: 1
}, {
label: 'apples',
value: 2
}, {
label: 'milk',
value: 3
}, {
label: 'tea',
value: 4
}, {
label: 'oranges',
value: 5
}, {
label: 'bread',
value: 6
}, {
label: 'cheese',
value: 7
}, {
label: 'apple-sauce',
value: 8
}, {
label: 'cream-cheese',
value: 9
}];
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#tags")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).autocomplete("instance").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function(request, response) {
// delegate back to autocomplete, but extract the last term
var list = $.ui.autocomplete.filter(availableTags, extractLast(request.term));
if (request.term) {
var regex = new RegExp('(' + $.ui.autocomplete.escapeRegex(request.term) + ')', "gi");
list = list.map(function(item) {
return {
label: item.label.replace(regex, '<b>$1</b>'),
value: item.value
}
})
}
response(list);
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("#tags").data('uiAutocomplete')._renderItem = function(ul, item) {
return $("<li>").append(item.label).appendTo(ul);
};
});
<link rel="stylesheet" type="text/css" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<div>
<label for="tags">Snack foods:</label>
<input id="tags" size="50">
</div>
Just used a create option to prepare HTML that needs to be rendered.
Below is the piece of that code. Although I know that this is not optimized one but you can do that yourself. But I think this is what you require.
Here is working JSFiddle https://jsfiddle.net/mgjftrdz/2/
create: function () {
$(this).data('ui-autocomplete')._renderItem = function (ul, item) {
var startIndex = item.label.indexOf($("#tags" ).val())
var endIndex = startIndex + $("#tags" ).val().length;
var totalLength = $("#tags" ).val();
var arr = item.label.split('');
var newLabel="<label>";
for(var i=0 ; i < arr.length; i++){
newLabel+= (i>= startIndex && i <= endIndex) ? "<b>"+arr[i]+"</b>": arr[i];
}
newLabel += "</label>"
return $('<li>')
.append('<a>' + newLabel + '</a>')
.appendTo(ul);
};
},
JSFiddle: https://jsfiddle.net/ealonwang/7y25ru40/
I am implementing the typeahead function. It seems that ng-model does not work with autocomplete.
Here is my code.
HTML:
<input type="text" id="origin" ng-model="searchForm.origin" placeholder="City, State">
AngularJS:
var origin = ["DALLAS, TX", "DALLAS, NE"];
$("#origin").autocomplete({
source: origin,
autoFocus: true,
delay: 0,
minLength: 3
});
When I type DAL in the input and select DALLAS, TX from the dropdown list, I actually get DAL for ng-model. Anyone has a solution? Thanks in advance.
I have to create a directive for this.
app.directive("autoComplete", function ($timeout) {
return {
restrict: "A",
link: function (scope, element) {
var location = ["OMAHA, NE", "OMAHA, TX", "DALLAS, TX", "DALLAS, NE"];
element.autocomplete({
source: location,
autoFocus: true,
delay: 0,
minLength: 3,
select: function () {
$timeout(function () {
element.trigger("input");
}, 0);
}
});
}
}
});
<form id="form1">
<input type="text" name="idEmp[]" class="idEmp">
<input type="text" name="nameEmp[]" class="nameEmp">
<input type="text" name="idEmp[]" class="idEmp">
<input type="text" name="nameEmp[]" class="nameEmp">
</form>
and the jquery here
$('.idEmp').on("focus", function(){
$(this).autocomplete({
minLength: 1,
source: "autocomplete.php",
focus: function(event, ui){
$(this).val(ui.item.id);
return false;
},
select: function(event, ui){
$(this).val(ui.item.id);
// something else here to show name in nameEmp fields
return false
}
})
.autocomplete("instance")._renderItem = function(ul, item){
return $("<li class='list-group-item list-group-item-info'>")
.append("<a><h5>Emp. ID : "+item.id+"<br><span class='badge'>"+item.name+"</span></h5></a>")
.appendTo(ul);
};
});
i want to apply jQuery autocomplete in each idEmp class then value of ID appears in idEmp[] and value name appears in nameEmp[]. is there anyone know this? thanks in advance!
Start typing jQuery and select the autocomplete option then fields would be populated with label and description, use below code as reference to your code.
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
$( ".idEmp" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( this ).val( ui.item.label );
$( this ).next( ".nameEmp" ).val( ui.item.desc );
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css"></link>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
Start typing jQuery and select the autocomplete option
<form id="form1">
<input type="text" name="idEmp[]" class="idEmp">
<input type="text" name="nameEmp[]" class="nameEmp"><br/>
<input type="text" name="idEmp[]" class="idEmp">
<input type="text" name="nameEmp[]" class="nameEmp">
</form>