I am still learning javascript and Jquery. I am creating simple autocomplete with jQuery:
<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() {
$( "#nazov" ).autocomplete({
minLength: 2,
source: 'private/search.php',
select: function(event, ui) {
document.getElementById("pocet").value = ui.item.pocet;
}
});
});
<label for="nazov">Názov: </label>
<input id="nazov">
<input id="pocet">
I have some basic JS function to create inputs. Every new input has id="nazov" But autocomplete works only with non-dynamic inputs and every new input that is dynamically created do not work.
I think it is because autocomplete function do not know about new input. It is any way to change autocomple to looking for new inputs and autocomplete each one with different return? I found some deprecated function .live() and .on() but I think I cannot use it here, or I do not know how.
Thanks for any help.
Have a nice day!
As a ID is unique you should not assign a ID twice. Use a class for this instead. So your code would look something like this:
JS:
$(function() {
$(".nazov").autocomplete({
minLength: 2,
source: 'private/search.php',
select: function(event, ui) {
document.getElementByClass("pocet").value = ui.item.pocet;
}
});
});
HTML:
<label for="nazov">Názov: </label>
<input class="nazov">
<input class="pocet">
Hope this helps
Related
I have a table with inputs. The user can start type and a JQuery script (https://jqueryui.com/autocomplete/#multiple) autocompletes users text.
The user can also add new inputs to the table with a simple JavaScript createElement and innerHTML function.
The problem arrives when the user adds the new inputs because JQuery doesn't register the new inputs and therefore it doesn't attach an event handler to autocomplete users text.
One solution that may work (but I couldn't get it to work) is the JQuery .delegate() function.
EDIT (Added source code):
https://jsfiddle.net/j8rz7s1q/7/
Can't get the code to format correctly from jsfiddle
From http://api.jquery.com/on/
Delegated event handlers have the advantage that they can process
events from descendant elements that are added to the document at a
later time.By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
Then, you just need to change the following example to match the elements that you have:
$( "#dataTable tbody" ).on( "click", "tr", function() {
console.log( $( this ).text() );
});
you need to use a delegate event to handle newly added elements
something like:
$(document).on("keydown", "tr input", function() {})
Ordinarily, binding an event on elements that do not exist yet is handled through delegation, where you bind on a parent element and rely on the event on any children created after the binding to work by bubbling up to the parent, which then can invoke the callback.
In the case of the jQuery UI Autocomplete plugin, it's implemented by applying the autocomplete to an element through its implemented interface, which does its own binding on the elements it's being used on.
In this case, where new DOM elements are being added, we define a function that handles binding the Autocomplete functionality on whatever elements are passed to it, and update the code that creates the new elements to call that function after creation to apply the Autocomplete bindings.
A working demonstration of this is in https://jsfiddle.net/j8rz7s1q/16 and duplicated here:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.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>
</head>
<body>
<button onClick="addInputs();" id="button1">Add input</button>
<p>
The first input works. The autocomplete works completely but when you add new inputs the new inputs doesn't register to the event handler.
</p>
<div>
<div class="LightBox-box-content">
<table>
<tbody class="addInput">
<tr>
<td>
<input type="text" class="input1">
</td>
</tr>
</tbody>
</table>
</div>
</div>
<script>
$(function() {
var availableTags = [
"Yes", "No",
];
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
window.setupAutocomplete = function($obj) {
return $obj
// don't navigate away from the field on tab when selecting an item
.on("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;
}
});
};
setupAutocomplete($(".input1"));
});
</script>
<script>
function addInputs() {
var div = document.createElement('tr');
div.innerHTML = '<tr>\
<td>\
<input type="text" class="input1">\
</td>\
</tr>';
setupAutocomplete($('input', div));
document.getElementsByClassName('addInput')[0].appendChild(div);
}
</script>
</body>
</html>
I am trying to fire the onSelect event as shown below but, it is not working.
I need to use datepicker object as per my application design.
var datePickerObject = $('#datepicker').datepicker();
datePickerObject.datepicker(
{
onSelect: function(dateText, inst) { alert("Working"); }
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
<input type="text" id="datepicker"/> //Updated as per Oscar jar suggestion
Any suggestion will be greatly appreciated.
Correct me if wrong but I think what you are doing wrong is that your datepicker component is getting initialized two times when invoking the datepicker(...) method for the first time when creating the datePickerObject and then again when adding other configurations (like your onSelect function) to the object that was already initialized (perhaps that's why it isn't working and your function is ignored since it's added in the second time).
So, if you avoid doing that and you only initialize the component for one time and use the configurations needed (see example from below) then you will get it working:
var cfg = {},
cmp = $('#datepicker');
// Add event handlers
cfg.onSelect = onDateSelect;
// Add other configs
cfg.changeMonth = true;
cfg.changeYear = true;
cfg.dateFormat = 'dd-mm-yy';
// Initialize component
cmp.datepicker(cfg);
function onDateSelect(date, cmp) {
console.log('Selected date is: %o', date);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
<div id="datepicker"></div>
On the other hand, I wonder why did you have the following in your code snippet:
<div type="text" id="datepicker"></div>
(Since the type attribute is not part of the div element)
If that's what you need then add an input for your datepicker component, like this:
<input type="text" id="datepicker"/>
UPDATE:
I've tested your code and passed your event handler when initializing the component only for the first time and it works:
var datePickerObject = $('#datepicker').datepicker({
onSelect: function(dateText, inst) {
alert('Working');
}
});
I just created an autocomplete textbox via jquery now i am stuck with two problems.
1) I need to get the value of the selected item from the Autocomplete list.
So far i did these..
My jquery
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
});
});
I am getting the autocomplete list from the database its working fine, but the problem is that
2) When i type 'r' all the names with values gets populated and if i select say Robin from the list and try to display it with alert, i only gets 'r', (i only typed r,and selected 'robin' from list) why is this so?
here is the code i wrote for this
for the autocomplete textbox
<input name="tags" type="text" id="tag" value="" onchange= "newfn()" />
and in newfn()
<script>
function newfn()
{
authname = document.getElementById("tag").value;
document.autoquote.qid.value=authname;
alert(authname);
}
</script>
and if i put an alert at first saying
alert("Hi");
then, i get first alert saying hi, and I get robin not r
So what is the correct way to get what value i selected from the autocomplete list?
Now my second Question is that the selected value from this autocomplete textbox, I need to pass it with another jquery to another php page so that I can get this value there and give it in a query as a criteria.
Because it is not the way to catch a select event http://api.jqueryui.com/autocomplete/#event-select :
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true,
select: function( event, ui ) {
//Then use "ui" object, for example ui.item.label or ui.item.value
}
});
});
$(".autosearch-smart").autocomplete('autocomplete.php', {
select: function( event, ui ) {
// here you can get id and values from the autocomplete list
// try to debug
console.log(ui.item.id);
console.log(ui.item.label);
console.log(ui.item.value);
}
});
you can use the autocomplete's select property like this
$("#tag").autocomplete('autocomplete.php', {
selectFirst: true,
select: function (event, ui) {
var label = ui.item.label;
var value = ui.item.value;
alert(label);
alert(value)
// you can write additional javascript code here to make use of these values
}
});
Please check the jQuery UI documentation for more examples and info.
Here is a JSFiddle.(Please note that an additional source attribute has been added in the fiddle to simulate the loading of data set as real cross domain AJAX calls are not allowed)
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
select: function( event, ui ) {
//check the values in console
alert(ui.item.value+" - "+ui.item.value);
}
});
});
I have simple jQuery UI autocomplete, which was working and now it's not. The code is as follows:
<html>
<head>
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.23.custom.min.js"></script>
<script type="text/javascript">
$(function() {
$( "#city" ).autocomplete({
source: function( request, response ) {
var cities = new Array();
cities.push({"label" : "Chicago", "value" : 1});
cities.push({"label" : "Houston", "value" : 2});
response(cities);
},
focus: function(event, ui) {
//console.log(ui.item.label);
$(this).text(ui.item.label);
//console.log($(this).text());
event.preventDefault();
//console.log($(this).text());
},
select: function(event, ui) {
//console.log($(this).text());
event.preventDefault();
//console.log($(this).text());
}
});
});
</script>
</head>
<body>
<input id="city" />
</body>
</html>
I am using the focus handler to show the label in the textbox instead of the value (which is what the autocomplete does by default). What is happening now is that the textbox is showing neither label nor value, it is showing the value that I have typed (say 'Chi')
This was working but now it's not. I thought it was because I had included some other javascript and there was a function name clash. But I moved it to a separate HTML as you can see above and it's still not working.
BTW if I uncomment those console log statements and from the dropdown I select Chicago, then all of them print Chicago.
This seems like some silly mistake somewhere but has me stumped. Any suggestions?
EDIT 1: BTW, if I remove the focus and select handlers then the autocomplete works with its default functionality.
EDIT 2: Would be great if someone can test this on their own computer
There are a couple of changes from default functionality which you appear to be attempting here.
You would like the "completed" variable to be previewed in the main input when it is selected
You would like the label, not the value, to be shown when a selection has been made.
The reasons that neither of these are currently working are related and simple: <input> fields only have a value associated with them, not a separate "label" and "value". When you select an "autocomplete" option from the list, it is the "value", which gets filled in.
For point 1, the part which is being updated by the focus: event, just replace .text(...) with .val(...), as that is the attribute of the <input> field which you actually want to update:
focus: function(event, ui) {
$(this).val(ui.item.label);
event.preventDefault();
},
For point 2, as you actually want the field to be filled in by the label, not the value, you could just fill in the same text for both (the default if a flat array is given):
source: function( request, response ) {
var cities = new Array();
cities.push("Chicago");
cities.push("Houston");
response(cities);
},
Remember that autocomplete is always optional. All you need to fill in for the value: is something which you back-end can fully disambiguate. That could be an id, but it usually makes sense to use something which the user might have typed in on their own. Of course, if you're doing that, it may also make sense to use ui.item.value instead of ui.item.label in the focus: event, as well.
With the source made sane as above, you can drop the select: event entirely.
I think the problem lies in the assignment of the autocomplete source. This works for me:
$(function() {
var cities = [
{"label": "Chicago", "value": 1},
{"label": "Houston", "value": 2}
];
$( "#city" ).autocomplete({
source: cities, // assign the source directly
focus: function(event, ui) {
//console.log(ui.item.label);
$(this).text(ui.item.label);
//console.log($(this).text());
event.preventDefault();
//console.log($(this).text());
},
select: function(event, ui) {
//console.log($(this).text());
event.preventDefault();
//console.log($(this).text());
}
});
});
here's a fiddle
I tried to search something similar but I failed, so, I'm asking here
this is a piece of my code:
<div id="ui-widget">
<label>Doc Type: </label>
<select id="classes" onchange="createForm()">
<option value=" ">Select a type ... </option>
<#list typenames?keys as key>
<#if typenames[key]!="">
<option value="${key}">${typenames[key]}</option>
</#if>
</#list>
</select>
</div>
the select tag is using this jQuery:
http://jqueryui.com/demos/autocomplete/#combobox
with autocomplete;
The function createForm() is a Javascript that creates different form depending on which selection you make in the select tag;
But using autocomplete from jQuery, the onchange event in the select tag seems not working.
Is there a method to inject some JavaScript code like my function to work on selection change of this jQuery?
Use the following to bind the autocompleteselect event for the autocomplete :
$( "#classes" ).autocomplete({
select: createForm
});
or
$( "#classes" ).autocomplete({
select: function(event, ui) {
// your code here
}
});
or
$( "#classes" ).bind( "autocompleteselect", function(event, ui) {
// your code here
});
Docs are here
You probably need to bind it to the autocomplete event autocompleteselect